I have data with some values ('value') and a grouping variable ('level'):
# Sample data frame
df <- data.frame(value = c(1,0,1,0,1,1,1,1,0,0),
level = c("A2","A3","A1","A2","A1","A3","A2","A1","A3","A2"))
value level
1 1 A2
2 0 A3
3 1 A1
4 0 A2
5 1 A1
6 1 A3
7 1 A2
8 1 A1
9 0 A3
10 0 A2
Conceptually, I assume that "A1" is the lowest level and "A3" the highest. I want to calculate mean value by including more and more groups in the calculation, like an 'expanding window', but based on entire groups, not on individual rows. Thus, for each group, the calculation will include values of the focal group and values in all other lower level groups.
I want the levels "A2" and "A3" to be inclusive. This means that when the focal level is "A2", the calculation includes values in group "A2" and values in the lower level "A1". When calculating the mean value of "A3", the calculation includes all values in the focal level "A3", and all lower levels, i.e. also values in group "A2" and "A1".
I aim to have an output like this:
MeanValue level
1 1.00 A1 # mean of level A1
2 0.71 A2 # mean of level A2 and A1
3 0.60 A3 # mean of level A3, A2, and A1
Could someone show me how to code this? I would really appreciate any help!