5

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:

  1. group_by x
  2. calculate cumsum for group b in column y
  3. take the last value (=15) of this group (=b) and
  4. put this value (=15) to column 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!!!

Peter
  • 11,500
  • 5
  • 21
  • 31
TarJae
  • 72,363
  • 6
  • 19
  • 66

2 Answers2

6

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
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
5

Just add the ungroup() before you calculate the 2nd mutate and use last with condition to get the last y with x == "b"

library(dplyr)

df %>% 
  group_by(x) %>% 
  mutate(y = case_when(x=="b" ~ cumsum(y),
    TRUE ~ y)) %>% 
  # add the ungroup here
  ungroup() %>%
  # and then the value is like this
  mutate(y = case_when(x=="a" ~ last(y[x == "b"]), 
    TRUE ~ y))
#> # A tibble: 12 x 2
#>    x         y
#>    <chr> <int>
#>  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

Created on 2021-04-22 by the reprex package (v2.0.0)

Sinh Nguyen
  • 4,277
  • 3
  • 18
  • 26