0

I have the following data frame:

 df <- data.frame(a=rep(1:3),b=rep(1:3),c=rep(4:6),d=rep(4:6))
    df
      a b c d
    1 1 1 4 4
    2 2 2 5 5
    3 3 3 6 6

i would like to have a vector N which determines my window size so for thsi example i will set

N <- 1

I would like to split this dataframe into equal portions of N rows and store the 3 resulting dataframes into a list.

I have the following code:

groupMaker <- function(x, y) 0:(x-1) %/% y

testlist2 <- split(df, groupMaker(nrow(df), N))

The problem is that this code renames my column names by adding an X0. in front

result <- as.data.frame(testlist2[1])

result
    X0.a X0.b X0.c X0.d
1    1    1    4    4
> 

I would like a code that does the exact same thing but keeps the column names as they are. please keep in mind that my original data has a lot more than 3 rows so i need something that is applicable to a much larger dataframe.

talat
  • 68,970
  • 21
  • 126
  • 157
Alex Bădoi
  • 830
  • 2
  • 9
  • 24

1 Answers1

2

To extract a list element, we can use [[. Also, as each list elements are data.frames, we don't need to explicitly call as.data.frame again.

testlist2[[1]]

We can also use gl to create the grouping variable.

split(df, as.numeric(gl(nrow(df), N, nrow(df))))
akrun
  • 874,273
  • 37
  • 540
  • 662