Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr中字符串的新列_R_Dplyr - Fatal编程技术网

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