【问题标题】:Randomly split a data table and make output files in R随机拆分数据表并在R中制作输出文件
【发布时间】:2020-01-31 00:57:42
【问题描述】:

我想将一个数据表随机拆分为 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="")

【问题讨论】:

  • 也许是dt[, fwrite(.SD, paste0(.BY, ".csv")), sample(1:n, nrow(dt), replace=TRUE)]
  • 你可以遍历'test'lapply(names(test), function(nm) fwrite(test[[nm]], paste0("output", nm, ".txt')))的名字
  • 有什么办法不在输出文件中包含每个列表的标题?

标签: r split data.table write.table


【解决方案1】:

我们可以使用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"))

或者如cmets中提到的@chinsoon12,指定col.names = FALSEfwrite默认为TRUE)

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

【讨论】:

  • 这可能很挑剔,但有没有办法不在每个列表中包含标题?
  • @ConnorMurray。您的意思是不包括列名吗?
  • @ConnorMurray 是data.table的列名。如果您想在没有列名的情况下存储它,那么您可以使用 catlapply(names(test), function(nm) cat(test[[nm]][[1]], file = paste0("output", nm, ".txt"), sep = "\n"))
  • 你可以使用col.names=FALSE作为fwrite的参数
  • @ConnorMurray 您可以使用replicate 并指定带有样本数量的n,不确定您想要什么
【解决方案2】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 2017-03-10
    相关资源
    最近更新 更多