简体   繁体   English

按因素写的

[英]write.table by factors

Given this dataFrame: 鉴于此dataFrame:

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

The code to generate the data frame: 生成数据框的代码:

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

How can I generate the ff. 我怎样才能生成ff。 text files: 文本文件:

  • 2003.txt contains the numbers -24, 3, 88, and so on. 2003.txt包含数字-24,3,88等。
  • 2004.txt contains the numbers 152, 67, 100 and so on. 2004.txt包含数字152,67,100等。

I'm a bit lost on what to do. 我有点迷失了怎么做。 I'm thinking of making years as factors and then somehow combining it with 我想把多年作为因素,然后以某种方式将它与它结合起来

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

the plyr package and d_ply make this easy. plyr包和d_ply使这很容易。

define a function that writes your files: 定义一个写入文件的函数:

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

Then call it with d_ply : 然后用d_ply调用它:

d_ply(testDF, .(years), myfun)

Be careful with this though... cause it writes a bunch of files to your current working directory silently! 但要小心这一点......因为它会默默地将一堆文件写入当前的工作目录!

 sapply(testDF$years, function(x) 
    write.table(testDF[testDF$years==x,], file=paste(x, "txt", sep=".") )
    )

You would not want to set append=T. 你不想设置append = T. Could also use subset: 也可以使用子集:

sapply(testDF$years, function(x) 
    write.table(subset( testDF, years==x), file=paste(x, "txt", sep=".") )
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM