在尝试了几个选项后,我发现最快的是data.table::fwrite。就像@Gregor 在他的第一条评论中所说,它快了一个数量级,这值得加载额外的包。它也是产生更大文件的文件之一。 (另一个是readr::write_lines。感谢Calum You的评论,我忘记了这个。)
library(data.table)
library(readr)
set.seed(1) # make the results reproducible
n <- 1e6
x <- rnorm(n)
t1 <- system.time({
sink(file = "test_sink.txt")
cat(x, "\n")
sink()
})
t2 <- system.time({
cat(x, "\n", file = "test_cat.txt")
})
t3 <- system.time({
write(x, file = "test_write.txt")
})
t4 <- system.time({
fwrite(list(x), file = "test_fwrite.txt")
})
t5 <- system.time({
write_lines(x, "test_write_lines.txt")
})
rbind(sink = t1[1:3], cat = t2[1:3],
write = t3[1:3], fwrite = t4[1:3],
readr = t5[1:3])
# user.self sys.self elapsed
#sink 4.18 11.64 15.96
#cat 3.70 4.80 8.57
#write 3.71 4.87 8.64
#fwrite 0.42 0.02 0.51
#readr 2.37 0.03 6.66
在他的第二条评论中,Gregor 指出 as.list 和 list 的行为不同。区别很重要。前者将向量写入一行多列,后者写入一列多行。
速度差异也很明显:
fw1 <- system.time({
fwrite(as.list(x), file = "test_fwrite.txt")
})
fw2 <- system.time({
fwrite(list(x), file = "test_fwrite2.txt")
})
rbind(as.list = fw1[1:3], list = fw2[1:3])
# user.self sys.self elapsed
#as.list 0.67 0.00 0.75
#list 0.19 0.03 0.11
最后清理。
unlink(c("test_sink.txt", "test_cat.txt", "test_write.txt",
"test_fwrite.txt", "test_fwrite2.txt", "test_write_lines.txt"))