dplyr中来自String的新列 [英] New Column from String in dplyr

查看:68
本文介绍了dplyr中来自String的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

library(tidyverse)

df <- tribble(~col1, ~col2, 1, 2)

现在我想创建一列。我在字符串中有新列的名称。它确实是这样工作的:

Now I want to create a column. I have the name of the new column in a string. It does work like this:

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

如何创建一个新列,该列的名称来自

How do I create a new column that gets its name from a string in an object?

推荐答案

在定义运算符中使用 !! := ,如此处所述,以将变量名设置为列名。

Use !! with the definition operator := as mentioned here, to set a variable name as the column name.


:=支持在LHS和RHS上都取消引用

:= supports unquoting on both the LHS and the RHS



library(dplyr)
newColumnName <- "col3"
df %>% mutate(!!newColumnName := 3)

# A tibble: 1 x 3
   col1  col2  col3
   <dbl> <dbl> <dbl>
1     1     2     3

这篇关于dplyr中来自String的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆