简体   繁体   中英

write.table by factors

Given this 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. text files:

  • 2003.txt contains the numbers -24, 3, 88, and so on.
  • 2004.txt contains the numbers 152, 67, 100 and so on.

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.

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(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. Could also use subset:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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