我有一个数据框:
library(tidyverse)
df <- tribble(~col1, ~col2, 1, 2)
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个列。我在字符串中有新列的名称。它确实像这样工作:
df %>%
mutate("col3" = 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
Run Code Online (Sandbox Code Playgroud)
但它不是这样工作的:
newColumnName <- "col3"
df %>%
mutate(newColumnName = 3)
# A tibble: 1 x 3
col1 col2 newColumnName
<dbl> <dbl> <dbl>
1 1 2 3
Run Code Online (Sandbox Code Playgroud)
如何创建一个从对象中的字符串获取其名称的新列?
!!与此处:=提到的定义运算符一起使用,将变量名设置为列名。
:= 支持在 LHS 和 RHS 上取消引用
library(dplyr)
newColumnName <- "col3"
df %>% mutate(!!newColumnName := 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
Run Code Online (Sandbox Code Playgroud)