I want to put a conditional term after the ~
in a case_when
function.
My example:
df:
df <- structure(list(x = c("a", "a", "a", "b", "b", "b", "c", "c",
"c", "a", "a", "a"), y = 1:12), class = "data.frame", row.names = c(NA,
-12L))
Not working code:
library(dplyr)
df %>%
group_by(x) %>%
mutate(y = case_when(x=="b" ~ cumsum(y),
TRUE ~ y)) %>%
mutate(y = case_when(x=="a" ~ "what I want: last value of group "b" in column y",
TRUE ~ y))
In words:
group_by
x
- calculate
cumsum
for groupb
in columny
- take the last value (=15) of this group (=b) and
- put this value (=15) to column
y
where group isa
desired output:
x y
<chr> <dbl>
1 a 15
2 a 15
3 a 15
4 b 4
5 b 9
6 b 15
7 c 7
8 c 8
9 c 9
10 a 15
11 a 15
12 a 15
Many thanks!!!