This isn't a duplicate of this question, since I'm asking to retain a column with a condition. I'd like to group a value in a column x
and sum the corresponding values in another column z
. I have the following data:
df <- data.frame(x = c("a", "a"),
y = c("a", "b"),
z = c(4, 5))
x y z
a a 4
a b 5
I can use summarise()
from dplyr
to do this, like so:
df %>%
group_by(x) %>%
summarise(z = sum(z))
x z
a 9
But I want to keep the column y
when x = y
, so the final output should look like this:
x y z
a a 9
How do I do this?