1

鉴于此数据框:

   years random_numbers
1   2003            -24
2   2004            152
3   2005             23
4   2006             73
5   2007             80
6   2008             85
.   ....             ..

生成数据框的代码:

years = c(rep(2003:2012,4))
random_numbers = as.integer(rnorm(40)*100)
testDF = data.frame(years, random_numbers)

我怎样才能生成ff。文本文件:

  • 2003.txt 包含数字 -24、3、88 等。
  • 2004.txt 包含数字 152、67、100 等。

我有点不知所措。我正在考虑将年份作为因素,然后以某种方式将其与

write.table(???, ???, append = T, row.names = F,  col.names = T)
4

2 回答 2

2

plyrd_ply让这很容易。

定义一个写入文件的函数:

myfun <- function(x) {
  filename <- paste0(unique(x$years), '.txt')
  write.table(x$random_numbers, filename, row.names=F, col.names=T)
}

然后调用它d_ply

d_ply(testDF, .(years), myfun)

不过要小心……因为它会默默地将一堆文件写入您当前的工作目录!

于 2012-08-22T22:20:45.657 回答
2
 sapply(testDF$years, function(x) 
    write.table(testDF[testDF$years==x,], file=paste(x, "txt", sep=".") )
    )

您不想设置 append=T。也可以使用子集:

sapply(testDF$years, function(x) 
    write.table(subset( testDF, years==x), file=paste(x, "txt", sep=".") )
    )
于 2012-08-22T23:48:01.057 回答