CCA
CCA

Reputation: 141

In R, how to create a loop to divide columns in a data frame

In R, I would like to create a loop which takes the first 3000 columns of my data frame and writes them into one file, the next 3000 columns into another file, and so on and so forth until all columns have been divided as such. What would be the best way to do this? I understand there are the isplit and iterators functions available now via CRAN, but I am really unsure how to go about this. Any suggestions please?

Upvotes: 3

Views: 1319

Answers (2)

Shane
Shane

Reputation: 100164

You could try something like:

library(plyr)
max.col <- ncol(x)
l_ply(seq(1, max.col, by=3000), function(i) 
    write.table(x[,i:min(i+2999, max.col)], file=paste("i", i, sep="-"))
)

Upvotes: 9

John
John

Reputation: 23758

Not sure why you'd bother loading plyr... assuming your data frame is df... (stole the wise use of min() from Shane's answer)

maxCol <- ncol(df)
for (i in seq(1, maxCol, by 3000)) {
     write.table(df[,i:min(i+2999, maxCol)], "i")
}

You may want to edit the write.table command above to add in your preferred formatting.

Upvotes: 1

Related Questions