开发者

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

开发者 https://www.devze.com 2023-01-05 18:11 出处:网络
In R, I would like to create a loop which takes the first 3000 colu开发者_高级运维mns of my data frame and writes them into one file, thenext 3000 columns into another file, and so on and so forth unt

In R, I would like to create a loop which takes the first 3000 colu开发者_高级运维mns 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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消