# [R] Sum every n (4) observations by group

Peter Langfelder peter@|@ng|e|der @end|ng |rom gm@||@com
Sun Dec 19 19:49:59 CET 2021

I'm not sure I understand the task, but if I do, assuming your data
frame is assigned to a variable named df, I would do something like

sumNs = function(x, n)
{
if (length(x) %%n !=0) stop("Length of 'x' must be a multiple of 'n'.")
n1 = length(x)/n
ind = rep(1:n1, each = n)
tapply(x, ind, sum)
}
sums = tapply(df\$Value, df\$ID, sumNs, 4)

Peter

On Sun, Dec 19, 2021 at 10:32 AM Miluji Sb <milujisb using gmail.com> wrote:
>
> Dear all,
>
> I have a dataset (below) by ID and time sequence. I would like to sum every
> four observations by ID.
>
> I am confused how to combine the two conditions. Any help will be highly
> appreciated. Thank you!
>
> Best.
>
> Milu
>
> ## Dataset
> structure(list(ID = c("A", "A", "A", "A", "A", "A", "A", "A",
> "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C", "C", "C",
> "C", "C", "C"), Date = c(4140L, 4141L, 4142L, 4143L, 4144L, 4145L,
> 4146L, 4147L, 4140L, 4141L, 4142L, 4143L, 4144L, 4145L, 4146L,
> 4147L, 4140L, 4141L, 4142L, 4143L, 4144L, 4145L, 4146L, 4147L
> ), Value = c(0.000207232, 0.000240141, 0.000271414, 0.000258384,
> 0.00024364, 0.00027148, 0.000280585, 0.000289691, 0.000298797,
> 0.000307903, 0.000317008, 0.000326114, 0.00033522, 0.000344326,
> 0.000353431, 0.000362537, 0.000371643, 0.000380749, 0.000389854,
> 0.00039896, 0.000408066, 0.000417172, 0.000426277, 0.000435383
> )), class = "data.frame", row.names = c(NA, -24L))
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help