使用 write.csv 时防止将行名写入文件
Posted
技术标签:
【中文标题】使用 write.csv 时防止将行名写入文件【英文标题】:Prevent row names to be written to file when using write.csv 【发布时间】:2011-11-21 00:14:25 【问题描述】:命令:
t <- data.frame(v = 5:1, v2 = 9:5)
write.csv(t, "t.csv")
结果文件:
# "","v","v2"
# "1",5,9
# "2",4,8
# "3",3,7
# "4",2,6
# "5",1,5
如何防止具有行索引的第一列写入文件?
【问题讨论】:
【参考方案1】:为了完整起见,readr
包中的 write_csv()
速度更快,并且从不写入行名
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
如果您需要写出大数据,请使用data.table
包中的fwrite()
。它比write.csv
和write_csv
都快很多
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
下面是 Edouard 在他的网站上发布的 benchmark
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
【讨论】:
【参考方案2】:write.csv(t, "t.csv", row.names=FALSE)
来自?write.csv
:
row.names: either a logical value indicating whether the row names of
‘x’ are to be written along with ‘x’, or a character vector
of row names to be written.
【讨论】:
我很惭愧,因为我确实尝试过 ?write.csv 但是...谢谢 aix! 是的,诀窍是要理解这一列代表行名。 也许应该重命名它。以上是关于使用 write.csv 时防止将行名写入文件的主要内容,如果未能解决你的问题,请参考以下文章