我想在循环中动态调用变量的值。这是问题的一个例子。我是tidyverse的新手,不擅长使用习惯。
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]]
))
感谢您的帮助。
答案 0 :(得分:1)
我们需要使用:=
。另外,如果只有一个元素,则可以使用!!
mtcars.join %>%
mutate(!! temp.name := case_when(!! rlang::sym(sample.name) <= 20 ~ 0,
TRUE ~ !! rlang::sym(temp.name)))
# Car mpg cyl disp hp drat wt qsec vs am gear carb DUM_mpg
#1 Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 21.0
#2 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 21.0
#3 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 22.8
#4 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 21.4
#5 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 0.0
#6 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 0.0
#7 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 0.0
#...
#...