Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A couple of case_when() tricks | Alan Yeung #7

Open
utterances-bot opened this issue Nov 18, 2023 · 1 comment
Open

A couple of case_when() tricks | Alan Yeung #7

utterances-bot opened this issue Nov 18, 2023 · 1 comment
Labels
comment blog post comments

Comments

@utterances-bot
Copy link

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/

Copy link

You can use rlang like this:

iris_df %>% 
  mutate(across(c(Petal.Length, Petal.Width),
                ~ case_when(eval(rlang::sym(eval(paste0("flag_", cur_column())))) == 1 ~ NA_real_,
                            TRUE ~ .x))) %>% 
  select(contains("Petal"))

@alan-y alan-y added the comment blog post comments label Dec 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
comment blog post comments
Projects
None yet
Development

No branches or pull requests

3 participants