用paste0进行变异

Dou*_*Fir 1 r dplyr

连接字段名称时如何改变字段?

library(tidyverse)    
x <- "blah"
y <- "cyl"

mtcars %>% 
  mutate(paste0(x,y) := as.factor(cyl)) # "Error: The LHS of `:=` must be a string or a symbol"

mtcars %>% 
  mutate(paste0(x,y) = as.factor(cyl)) # Error: unexpected '=' in: "mtcars %>%  mutate(paste0(x,y) ="
Run Code Online (Sandbox Code Playgroud)

我如何最终得到一个名为“blahcyl”的新字段,它是 cyl 的一个因子?

Ron*_*hah 7

评估字符串!!

library(dplyr)
mtcars %>% mutate(!!paste0(x,y) := as.factor(cyl))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb blahcyl
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4       6
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4       6
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1       4
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1       6
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2       8
#...
Run Code Online (Sandbox Code Playgroud)

  • 我不确定情况是否总是如此,但一般来说,如果您想添加名称为“string”的新列,请使用“!!string :=”,如果您想使用“string”作为列名来执行任何操作使用 `!!sym(string)`。 (2认同)