如何在R中写出具有不同文件名的多个文件

问题描述:

我有一个BIG文件(> 10000行数据),我想按ID写入一个单独的文件.我有50个唯一的ID名称,并且每个名称都需要一个单独的文本文件.这是我到目前为止所得到的,而且我一直在出错.我的ID实际上是字符串,如果可以用该字符串命名每个文件,则最好使用它.

I have one BIG file (>10000 lines of data) and I want write out a separate file by ID. I have 50 unique ID names and I want a separate text file for each one. Here's what Ive got so far, and I keep getting errors. My ID is actually character string which I would prefer if I can name each file after that character string it would be best.

for (i in 1:car$ID) {
    a <- data.frame(car[,i])
    carib <- car1[,(c("x","y","time","sd"))]
    myfile <- gsub("( )", "", paste("C:/bridge", carib, "_", i, ".txt"))
    write.table(a, file=myfile,
                sep="", row.names=F, col.names=T quote=FALSE, append=FALSE) 
}

一种方法是使用plyr软件包和d_ply()函数. d_ply()希望将data.frame作为输入.您还提供了一列,您希望对该data.frame进行切片和切分以彼此独立地进行操作.在这种情况下,您将具有列ID.这个特定的函数不会返回任何对象,因此对于绘图或迭代制作宪章等很有用.这是一个小的工作示例:

One approach would be to use the plyr package and the d_ply() function. d_ply() expects a data.frame as an input. You also provide a column(s) that you want to slice and dice that data.frame by to operate on independently of one another. In this case, you have the column ID. This specific function does not return an object, and is thus useful for plotting, or making charter iteratively, etc. Here's a small working example:

library(plyr)

dat <- data.frame(ID = rep(letters[1:3],2) , x = rnorm(6), y = rnorm(6))

d_ply(dat, "ID", function(x)
     write.table(x, file = paste(x$ID[1], "txt", sep = "."), sep = "\t", row.names = FALSE))

将使用ID列作为文件名(a.txt,b.txt,c.txt)生成三个制表符分隔的文件.

Will generate three tab separates files with the ID column as the name of the files (a.txt, b.txt, c.txt).

编辑-解决后续问题

在将其传递到d_ply()之前,您始终可以对所需的列进行子集化.另外,您可以使用/滥用[运算符,然后在调用本身中选择所需的列:

You could always subset the columns you want before passing it into d_ply(). Alternatively, you can use/abuse the [ operator and select the columns you want within the call itself:

dat <- data.frame(ID = rep(letters[1:3],2) , x = rnorm(6), y = rnorm(6)
  , foo = rnorm(6))

d_ply(dat, "ID", function(x)
     write.table(x[, c("x", "foo")], file = paste(x$ID[1], "txt", sep = ".")
     , sep = "\t", row.names = FALSE))