2

The top post of this question helped me equally divide a vector into an even set of chunks:

Split a vector into chunks in R

My problem now is that I would like to construct data frames out of the output. Here is the problem in R syntax:

d <- rpois(73,5)
solution1 <- split(d, ceiling(seq_along(d)/20))
ERROR <- as.data.frame(solution1)

The error that you should see is "arguments imply differing number of rows." I'm especially confused because I thought that the as.data.frame() function could handle this problem, as evident here:

http://www.r-bloggers.com/converting-a-list-to-a-data-frame-2/

Thanks for all your help!

EDIT 1:

I am close to a solution with this line, however, there are NA values that are being introduced that distort the output that I seek:

ldply(solution1,data.frame)

ldply is from the plyr package

Community
  • 1
  • 1
jonnie
  • 745
  • 1
  • 13
  • 22

1 Answers1

2

Did you read the ?split help page? Did you notice the unsplit() function? That sounds like exactly what you're trying to do here.

d <- rpois(73,5)
f <- ceiling(seq_along(d)/20) #factor for splitting
solution1 <- split(d, f)
unsplit(solution1 , f)

I'm not sure what you expected your data.frame to look like, but the error message you got was because as.data.frame() was trying to create a new column in your data.frame for each item in solution1. And since each of those vectors in the list has a different number of elements, you cannot make a data.frame from that. A data.frame requires that every column has the same number of rows.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Very good solution for splitting data frame. I need additional help on this, I want the 4 lists got created in this process to be 4 separate data frames so that I can use them further. I want them locally available. Please help, use the above as an example. – JK1185 Feb 11 '21 at 15:42