1

我想在循环中动态调用变量的值。这是问题的一个例子。我是 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]]
))

谢谢您的帮助。

4

1 回答 1

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
#...
#...
于 2018-11-23T16:28:57.360 回答