I'm working to create factor variables from numeric column, but i want to use listed value as parameter for desired column. I have been able to select a column based on vector input but still unable to do it inside mutate case_when
var1 = "transfer"
var2 = "transfer_tier"
tier <- trx %>%
select_(.dots = var1) %>%
mutate_(var2 = case_when(
var1 <= 1e3 ~ '1. <1k',
var1 <= 1e4 ~ '1. <10k',))
using above code shows no error but the formula that i want does not work. var2 is created with all NA. how to call var1 properly?
CodePudding user response:
I can't reproduce your issue because I don't have your data, so here is a minimal reproducible example showing how to use as.name()
and/or the "curly curly" syntax to bring names from 'external' vectors in your tidyverse workflow:
library(tidyverse)
#install.packages("palmerpenguins")
library(palmerpenguins)
var1 <- "body_mass_g"
var2 <- "island"
penguins %>%
select(external_var1 = as.name(var1),
external_var2 = {{var2}}) %>%
mutate(categorised_var1 = case_when(
external_var1 <= 3500 ~ "skinny",
external_var1 >= 5500 ~ "heavy",
TRUE ~ "regular"
)) %>%
ggplot(aes(y = categorised_var1, fill = external_var2))
geom_bar()
Created on 2021-12-01 by the reprex package (v2.0.1)
In this case as.name() and curly curly syntax are interchangeable, but that might not be the case with your real data; please see How to make a great R reproducible example for tips on how to help us help you.