0

I have a number of dataframes, each with different numbers of rows. I want to break them all into smaller dataframes that have no more than 50 rows each, for example.

So, if I had a dataframe with 107 rows, I want to output the following:

A dataframe containing rows 1-50
A dataframe containing rows 51-100
A dataframe containing rows 101-107

I have been reading many examples using the split() function but I have not been able to find any usage of split() or any other solution to this that does not pre-define the number of dataframes to split into, or scrambles the order of the data, or introduce other problems.

This seems like such a simple task that I am surprised that I have not been able to find a solution.

user5359531
  • 3,217
  • 6
  • 30
  • 55
  • 5
    `split(df,(seq_len(nrow(df))-1) %/% 50)` – nicola Mar 16 '16 at 17:26
  • 1
    Thanks, this seems to work. Would you mind making this an Answer for the question, maybe with a little explanation of how it works? The second argument in `split()` is a little confusing. – user5359531 Mar 16 '16 at 17:31
  • Done as requested, even if I suspect that your question is a dupe. – nicola Mar 16 '16 at 17:37
  • 1
    Possible duplicate of [Split a vector into chunks in R](http://stackoverflow.com/questions/3318333/split-a-vector-into-chunks-in-r) – Henrik Mar 16 '16 at 17:55

1 Answers1

4

Try:

split(df,(seq_len(nrow(df))-1) %/% 50)

What have in common the first 50 rows? If you make an integer division (%/%) of the index of row (less one) by 50, they all give 0 as result. As you can guess, rows 51-100 give 1 and so on. The (seq_len(nrow(df))-1) %/% 50 basically indicate the group you want to split into.

nicola
  • 24,005
  • 3
  • 35
  • 56
  • Thanks again. "What have in common the first 50 rows?"; this is the problem with all the other examples I have found on StackOverflow using `split()` - they all assume that the rows have something in common and try to split based on this. Mine have nothing in common, thus none of the myriad other examples for this function work. – user5359531 Mar 16 '16 at 17:47