我想在循环中动态调用变量的值。这是问题的一个例子。我是 tidyverse 的新手,不擅长 quos 和 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"))
这给出了所需的输出:
mtcars.join <- mtcars.join %>% mutate (DUM_mpg = case_when(
mpg <= 20 ~ 0,
TRUE ~ mpg
))
但是,如上所述,我在循环中使用它并且需要调用变量名:temp.name
并且sample.name
在循环内动态调用。以下是我失败的尝试。
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]]
))
谢谢您的帮助。