split dataframe by row number in R

后端 未结 2 1891
Happy的楠姐
Happy的楠姐 2021-01-05 06:05

This is probably really simple, but I can\'t find a solution:

df <- data.frame(replicate(10,sample(0:1,10,rep=TRUE)))

v <- c(3, 7)

i

2条回答
  •  长情又很酷
    2021-01-05 06:41

    Assuming that rows 1&2 goes in the first split, 3,4,5,6 in the second and 7 to nrow(df) goes in the last

     split(df, cumsum(1:nrow(df) %in% v))
    

    but if 1:3 rows are in the first split, then comes 4:7, and in the third 8 to nrow(df)

      split(df, cumsum(c(TRUE,(1:nrow(df) %in% v)[-nrow(df)])) )
    

    Or as @James mentioned in the comments,

      split(df, cumsum(1:nrow(df) %in% (v+1)))
    

提交回复
热议问题