dplyr中字符串的新列
我有一个数据帧:dplyr中字符串的新列,r,dplyr,R,Dplyr,我有一个数据帧: library(tidyverse) df <- tribble(~col1, ~col2, 1, 2) 库(tidyverse) df% 突变(“col3”=3) #一个tibble:1 x 3 col1 col2 col3 1 1 2 3 但它不是这样工作的: df %>% mutate("col3" = 3) # A tibble: 1 x 3 col1 col2 col3 <dbl> <
library(tidyverse)
df <- tribble(~col1, ~col2, 1, 2)
库(tidyverse)
df%
突变(“col3”=3)
#一个tibble:1 x 3
col1 col2 col3
1 1 2 3
但它不是这样工作的:
df %>%
mutate("col3" = 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
newColumnName <- "col3"
df %>%
mutate(newColumnName = 3)
# A tibble: 1 x 3
col1 col2 newColumnName
<dbl> <dbl> <dbl>
1 1 2 3
newColumnName%
变异(newColumnName=3)
#一个tibble:1 x 3
col1 col2 newColumnName
1 1 2 3
如何创建从对象中的字符串获取名称的新列?使用
使用前面提到的定义运算符:=
,将变量名设置为列名
:=在左侧和右侧都支持取消引用
库(dplyr)
newColumnName%变异(!!newColumnName:=3)
#一个tibble:1 x 3
col1 col2 col3
1 1 2 3
library(dplyr)
newColumnName <- "col3"
df %>% mutate(!!newColumnName := 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3