I would like to recall the value of the variable dynamically in a loop. Here is an example of the problem. I am new to tidyverse and not great at quos and quosures.
library (tidyverse)
mtcars.df <- mtcars
mtcars.df <- mtcars.df %>% rownames_to_column( var = "Car")
temp.df <- mtcars %>% select(mpg, cyl, disp)
temp.df <- temp.df %>% rownames_to_column( var = "Car")
sample.name.temp <- "mpg_temp"
sample.name <- unlist(strsplit(as.character(sample.name.temp), '_', fixed = TRUE))[1]
names (temp.df)[2] <- paste0("DUM_", sample.name)
temp.name <- paste0("DUM_", sample.name)
mtcars.join <- full_join(mtcars.df, temp.df, by = c("cyl", "disp", "Car"))
This gives the desired output:
mtcars.join <- mtcars.join %>% mutate (DUM_mpg = case_when(
mpg <= 20 ~ 0,
TRUE ~ mpg
))
However, as noted above I am using this in a loop and need to recall the variable names: temp.name
and sample.name
dynamically within the loop. Below are my failed attempts.
mtcars.join <- mtcars.join %>% mutate (!!!temp.name = case_when(
!!!sample.name <= 20 ~ 0,
TRUE ~ !!!temp.name
))
mtcars.join <- mtcars.join %>% mutate (!!!rlang::syms(temp.name) = case_when(
!!!rlang::syms(sample.name) <= 20 ~ 0,
TRUE ~ !!!rlang::syms(temp.name)
))
mtcars.join <- mtcars.join %>% mutate (!!!rlang::syms(temp.name) = case_when(
!!!rlang::syms(sample.name) <= 20 ~ 0,
TRUE ~ !!!rlang::syms(temp.name)
))
mtcars.join <- mtcars.join %>% mutate (!!temp.name = case_when(
!!sample.name <= 20 ~ 0,
TRUE ~ !!temp.name
))
mtcars.join <- mtcars.join %>% mutate (mtcars.join[[temp.name]] = case_when(
mtcars.join [[sample.name]] <= 20 ~ 0,
TRUE ~ mtcars.join [[temp.name]]
))
Thanks for the help.
We need to use
:=
. Also, if there is a single element, evaluation can be done with!!