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
cumsum for group b in column y
y where group is a
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!!!
case_when with a single case To do this syntactically, we simply type the name of the function: case_when() . Then, inside the parenthesis, there is an expression with a “left hand side” and a “right hand side,” which are separated by a tilde ( ~ ).
This function allows you to vectorise multiple if and else if statements. It is an R equivalent of the SQL CASE WHEN statement.
Similarly to readr , dplyr and tidyr are also part of the tidyverse. These packages were loaded in R's memory when we called library(tidyverse) earlier.
In this case, group_by() is not necessary (although it helps to readability etc.):
df %>%
 mutate(y = case_when(x == "b" ~ cumsum(y * (x == "b")),
                      x == "a" ~ max(cumsum(y[x == "b"])),
                      TRUE ~ y))
   x  y
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With