Is it possible to use write.table () and ddply together?

Let's say I have data.frame like:

a <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10) df <- data.frame(a,rnorm(100)) 

And I want to write a csv file for each x value. Can this be done with ddply?

I can already do this with a for loop on several lines ... but I'm curious if this can be done with ddply.

 for (x in 1:nrow(unique(df["a"]))) { tmp <- unique(df["a"]) tmp2 <- paste(tmp[x,],".csv", sep="") write.table(subset(df, a == tmp[a,], drop=T),file=tmp2, sep=",", row.names=F) } 
+4
source share
2 answers

Continuing to answer Joshua's questions, the plyr function that should be used is d_ply , which does not expect to return anything. You can do something like this:

 d_ply(df, .(a), function(sdf) write.csv(sdf, file=paste(sdf$a[[1]],".csv",sep=""))) 

The file argument for write.csv constructed in such a way that each subset gets a different file name.

+4
source

This can be done with ddply , but that’s not what the function is for. From the plyr documentation:

All plyr functions use the same split-apply-comb strategy ...

You want to split data.frame and apply the function, but you don't want to return anything, so ddply will ddply error if you don't return something that can be combined into data.frame.

+1
source

All Articles