You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Combining case_when() and across()
If you want to use case_when() and across() different variables, then here is an example that can do this with the help of the get() and cur_column() functions.
library(tidyverse)
iris_df <- as_tibble(iris) %>% mutate(flag_Petal.Length = as.integer(Petal.Length > 1.5),
flag_Petal.Width = as.integer(Petal.Width > 0.2))
iris_df %>% mutate(across(c(Petal.Length, Petal.Width),
~case_when(
get(glue::glue("flag_{cur_column()}")) == 1 ~ NA_real_,
TRUE ~ .x
))) %>% select(contains("Petal"))
A couple of case_when() tricks | Alan Yeung
Combining case_when() and across()
If you want to use case_when() and across() different variables, then here is an example that can do this with the help of the get() and cur_column() functions.
library(tidyverse)
iris_df <- as_tibble(iris) %>% mutate(flag_Petal.Length = as.integer(Petal.Length > 1.5),
flag_Petal.Width = as.integer(Petal.Width > 0.2))
iris_df %>% mutate(across(c(Petal.Length, Petal.Width),
~case_when(
get(glue::glue("flag_{cur_column()}")) == 1 ~ NA_real_,
TRUE ~ .x
))) %>% select(contains("Petal"))
# A tibble: 150 × 4
Petal.
https://alan-y.netlify.com/post/couple-of-casewhen-tricks/
The text was updated successfully, but these errors were encountered: