我有一个数据框:
library(tidyverse)
df <- tribble(~col1, ~col2, 1, 2)
现在我想创建一个专栏。我有一个字符串中的新列的名称。它确实像这样工作:
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
如何创建一个从对象中的字符串获取其名称的新列?
Use !!
与定义运算符:=
如上所述here https://dplyr.tidyverse.org/articles/programming.html,将变量名称设置为列名称。
:= 支持在左侧和右侧取消引用
library(dplyr)
newColumnName <- "col3"
df %>% mutate(!!newColumnName := 3)
# A tibble: 1 x 3
col1 col2 col3
<dbl> <dbl> <dbl>
1 1 2 3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)