随机拆分数据表并在R中制作输出文件



我想将数据表随机拆分为n个输出;然后我想为每个列表编写这些输出。因此,在测试中,我想为测试中的每个列表编写一个文件。

library(data.table)
set.seed(100)
dt <- data.table(x=rnorm(1000))
n <- 10 # number of data sets
# randomly splits dt into n number of outputs
test <- split(dt, sample(1:n, nrow(dt), replace=T))
# writing tables for each sublist within test
# write.table(test)
# names <- paste0("output", n, ".txt", sep="")

我们可以使用fwrite,因为它是一种data.table并且速度更快

library(data.table)
lapply(names(test), function(nm) fwrite(test[[nm]], paste0("output", nm, ".txt")))

header"x"是列名,如果我们需要一些自定义格式,可以使用cat

lapply(names(test), function(nm) 
cat(test[[nm]][[1]], file = paste0("output", nm, ".txt"), sep = "n"))

或者@chinsoon12注释中提到的,指定col.names = FALSE(默认情况下,它在fwrite中为 TRUE(

lapply(names(test), function(nm) fwrite(test[[nm]],
paste0("output", nm, ".txt"), col.names = FALSE))

你可以做:

lapply(seq_along(test), function(x) 
write.table(test[[x]], file = paste0('output', x, '.txt')))

最新更新