Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

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

Let's say I have a 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 be able to write a csv file for each value of x. Is it possible to do this with ddply?

I can already do this with a for loop in a few lines... but I'm curious if it's possible to do it 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)
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Continuing from Joshua's answer, the plyr function to use 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 to write.csv is constructed such that each subset gets a different filename.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...