Black
Black

Reputation: 4644

R: Split dataset by n

I have a dataset like

day | group1 | group2 | group3
1   |   12   |   23   |   23
2   |   23   |   12   |   21
3   |   17   |   19   |    8
4   |   16   |   32   |   32
5   |   10   |   13   |   12

I would like to split the dataset into days between 1 - 7, 8 - 14, 14 - 20 etc. and run a forecasting method on each of these datasets.

How would I go about splitting the dataset into groups of 7?

Upvotes: 1

Views: 135

Answers (2)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Try:

id = c(0, df$day) %/% 7
split(df, head(id, -1))

Upvotes: 1

David Arenburg
David Arenburg

Reputation: 92292

I would go with a module of 7 combined with cumsum in order to create separate groups (assuming dat is your data set)

split(dat, cumsum(dat$day %% 7 == 1))

Or divide by 7 and use ceiling

split(dat, ceiling(dat$day / 7))

Upvotes: 4

Related Questions