R语言 写到CSV文件
对于数据分析,有时需要创建CSV数据文件,并根据我们的要求对其进行一些操作。因此,在这篇文章中,我们将学习如何使用R编程语言将数据写入CSV文件。
要写到CSV文件,需要使用write.csv()函数。
语法: write.csv(data, path)
参数
- data:要添加到csv的数据
- path:文件的路径名称
方法
- 创建一个DataFrame
- 将所需的值传递给函数
- 写入文件
让我们首先创建一个数据框。
例子
Country <- c("China", "India", "United States", "Indonesia", "Pakistan")
Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280",
"327,096,265", "267,670,543", "212,228,286")
Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754",
"329,064,917", "270,625,568", "216,565,318")
change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")
data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)
print(data)
输出
我们在控制台的数据
现在让我们把这些数据写入csv文件并保存到所需的位置。
例子
Country <- c("China", "India", "United States", "Indonesia", "Pakistan")
Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280",
"327,096,265", "267,670,543", "212,228,286")
Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754",
"329,064,917", "270,625,568", "216,565,318")
change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%")
data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)
print(data)
write.csv(data,"C:\\Users\\...YOUR PATH...\\population.csv")
print ('CSV file written Successfully :)')
输出
带有数据的CSV文件