I have a dataframe that looks like this:
data <- data.frame(a=c(1,1,0,0,0,0,1,1,1, 0),
b=c("x","x","x","x","x","y","y","y","z","z"),
c=c(2, 1, 2, 3, 4, NA, 4, 2, 1, 1),
d= c("s", "m", "l", "l", "l", "m", "m", "s", "s", "m"))
I would like to find a way to create a new variable, e, that is a sum of the values in c when a=1 for every combination of d and b. I've tried several options that aren't giving me what I'm looking for, for instance:
data <- data %>%
group_by(d, b) %>%
summarise (e = sum(data$c[which(data$a=="x")]))
Something that ultimately looks like:
d b e
1 s x 2
2 m x 1
3 l x 9
4 m y 4
5 s y 2
6 s z 1
7 s z 1
But unfortunately, I am only getting a constant e? Any help appreciated!
If you like, you can also just do this all in the summarise call:
We can use
Or