alki
alki

Reputation: 3584

R break up data frame into list using vector of number of rows

I have a data.frame that I want to break up into a list of data.frames using a vector that will tell me how many rows should be in each consecutive list element.

Sample Data

vectornom <- c(1,2,4,3)
df <- data.frame(x=1:10,y=11:20)

Desired result

> new_list
[[1]]
  x  y
  1 11
[[2]]
  x   y
  2  12
  3  13
[[3]]
  x   y
  4  14
  5  15
  6  16
  7  17
[[4]]
  x   y
  8  18
  9  19
  10 20

I appreciate your help

Upvotes: 2

Views: 531

Answers (1)

RichAtMango
RichAtMango

Reputation: 386

You can use the (pretty awesome) split function for this, using vectornom to create the index on which to "split"

split(df, rep(1:length(vectornom), vectornom))

Upvotes: 5

Related Questions