Skip to content
Prev 322840 / 398503 Next

Sum objects in a column between an interval defined by conditions on another column

Hi

Just a question. Why you do not sum 5 with 3 and 4 or leave 3 alone and sum 4 and 5?

Basically combination of cut and aggregate gives you what you want, but tricky is how to do the cut operation based on your requirements and data

aggregate(df$B, list(df$A), sum)

aggregates B for any single value of A.

However I am not sure how to change A to set of levels based on your description. For this particular df it can be done by

aggregate(df$B, list(cut(df$A, c(0,1,2,4,6))), sum)

But it is not a general solution.

Petr