Paolo
Paolo

Reputation: 1637

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:

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)

Upvotes: 1

Views: 289

Answers (2)

IRTFM
IRTFM

Reputation: 263451

 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=".") )
    )

Upvotes: 2

Justin
Justin

Reputation: 43265

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!

Upvotes: 2

Related Questions