R语言 如何写到CSV而不需要索引
我们知道,当我们把一些数据从DataFrame写到CSV文件时,会自动创建一列作为索引。我们可以通过一些修改来删除它。因此,在这篇文章中,我们将看到如何在R中写CSV而不需要索引。
要写成CSV文件,需要使用write.csv()。
语法:
write.csv(data,path)
让我们先看看当数据被写入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文件
现在让我们看看如何删除这些索引,为此只需在使用write.csv()函数将数据写入csv文件时将row.names参数设置为False。默认情况下,它将是TRUE,并在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)
write.csv(data,"C:\\Users\\..YOUR PATH...\\population.csv", row.names = FALSE)
print ('CSV file written Successfully :)')
输出
没有额外索引列的CSV文件