Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional term after the `~` in a `case_when` function

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!!!

like image 904
TarJae Avatar asked Apr 22 '21 07:04

TarJae


People also ask

How to use case_ when function?

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 ( ~ ).

What does case when do in R?

This function allows you to vectorise multiple if and else if statements. It is an R equivalent of the SQL CASE WHEN statement.

Is Dplyr in Tidyverse?

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.


Video Answer


1 Answers

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
like image 126
tmfmnk Avatar answered Sep 30 '22 08:09

tmfmnk