dplyr concat列存储在变量中(变异和非标准评估) [英] dplyr concat columns stored in variable (mutate and non standard evaluation)

查看:68
本文介绍了dplyr concat列存储在变量中(变异和非标准评估)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于变量cols_to_concat

df <- dplyr::data_frame(a = letters[1:3], b = letters[4:6], c = letters[7:9])
cols_to_concat = c("a", "b", "c")

要使用此特定值cols_to_concat达到所需的结果,我可以这样做:

To achieve the desired result with this specific value of cols_to_concat I could do this:

df %>% 
  dplyr::mutate(concat = paste0(a, b, c))

但是我需要使用类似这样的语法来概括这一点

But I need to generalise this, using syntax a bit like this

# (DOES NOT WORK)
df %>% 
  dplyr::mutate(concat = paste0(cols))

我想使用新的 NSE方法dplyr 0.7.0的(如果合适),但找不到正确的语法.

I'd like to use the new NSE approach of dplyr 0.7.0, if this is appropriate, but can't figure out the correct syntax.

推荐答案

您可以从rlang尝试syms:

library(dplyr)
packageVersion('dplyr')
#[1] ‘0.7.0’
df <- dplyr::data_frame(a = letters[1:3], b = letters[4:6], c = letters[7:9])
cols_to_concat = c("a", "b", "c")

library(rlang)
cols_quo <- syms(cols_to_concat)
df %>% mutate(concat = paste0(!!!cols_quo))

# or
df %>% mutate(concat = paste0(!!!syms(cols_to_concat)))

# # A tibble: 3 x 4
#       a     b     c concat
#   <chr> <chr> <chr>  <chr>
# 1     a     d     g    adg
# 2     b     e     h    beh
# 3     c     f     i    cfi

这篇关于dplyr concat列存储在变量中(变异和非标准评估)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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