JohnnyDeer JohnnyDeer - 3 months ago 20
R Question

Merging dataframe every x row

I am trying to merge values in a dataframe by every nth row.
The data structure looks as follows:

id value
1 1
2 2
3 1
4 2
5 3
6 4
7 1
8 2
9 4
10 4
11 2
12 1


I like to aggregate the values for every 4 rows each. Actually, the dataset describes a measurement for each a 4-day period. id"1"=day1, id"2"=day2, id"3"=day3, id"4"=day4, id"5"=day1,... As such, a column counting in a looĆ¼ from 1 to 4 might be used?

The result should look like (sums):

day sum
1 8
2 10
3 4
4 5

Answer

This can be achieved with %% for creating a grouping variable and then do the sum with aggregate

n <- 4
aggregate(value ~cbind(day = (seq_along(df1$id)-1) %% n + 1), df1, FUN = sum)
#   day value
#1   1     8
#2   2    10
#3   3     4
#4   4     5
Comments