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

In R, I would like to create a loop that takes the first 3000 columns of my data frame and writes them to one file, the next 3000 columns to another file, etc. etc. until all columns are separated as such. What would be the best way to do this? I understand that isplit and iterators functions are now available through CRAN, but I'm really not sure how to do this. Any suggestions please?

+3
source share
2 answers

You can 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="-"))
)
+9
source

Not sure why you need to load plyr ... if your df data frame ... (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")
}

write.table , .

+1

Source: https://habr.com/ru/post/1753386/


All Articles