连接字段名称时如何改变字段?
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 的一个因子?
评估字符串!!
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)
| 归档时间: |
|
| 查看次数: |
1414 次 |
| 最近记录: |