-1

I have a dataframe with this column:

1
1
1
1
2
2
2
2
3
3
3
3

And I want to sum it every n numbers (Say 4). Intended output:

4
8
12

How can I do this? I know how to do rollsum, but wanted to know if there is any function to do this?

maximusdooku
  • 5,242
  • 10
  • 54
  • 94
  • 4
    Your example is confusing. It may look like you want `sum` per each unique values. – akrun Jul 13 '15 at 18:49
  • Thank you. I didn't think that way. I just put those numbers for the sake of convenience of adding. :) – maximusdooku Jul 13 '15 at 18:59
  • All of the examples in the other question are for _vectors_; since yours is already in a `data.frame` (i.e. the declaration overhead there is out of the way), you might be better off with a `data.table` solution: `setDT(df)[,sum(v),by=.(rep(seq_len(nrow(df)%/%n),each=n))]` – MichaelChirico Jul 13 '15 at 19:04

1 Answers1

1
X <- data.frame(value = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3))
X$group = rep(1:(nrow(X)/4), each=4)

tapply(X$value, X$group, FUN = sum)

The hardest part here is assigning the groups. See ?rep for details there.

Benjamin
  • 16,897
  • 6
  • 45
  • 65