dplyr使用列名称的字符向量进行变异 [英] dplyr mutate using character vector of column names
本文介绍了dplyr使用列名称的字符向量进行变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
data是一个data.frame,包含:date,a,b,c,d列。后4个是数字
data is a data.frame containing: date, a, b, c, d columns. Last 4 is numeric
Y.columns <- c("a")
X.columns <- c("b","c","d")
我需要什么:
data.mutated <- data %>%
mutate(Y = a, X = b+c+d) %>%
select(date,Y,X)
但我想从字符向量传递mutate参数,
i尝试了以下操作:
but i would like to pass mutate arguments from character vector, i tried the following:
Y.string <- paste(Y.columns, collapse='+')
X.string <- paste(X.columns, collapse='+')
data.mutated <- data %>%
mutate(Y = UQ(Y.string), X = UQ(X.string)) %>%
select(date,Y,X)
但这没有用。
推荐答案
要将tidyeval与 UQ
一起使用,您首先需要使用 rlang
中的 parse_quosure
将表达式解析为等价的(使用 mtcars 例如code>,因为OP的问题不可重现):
To use tidyeval with UQ
, you need to first parse your expressions to a quosure with parse_quosure
from rlang
(Using mtcars
as example, since OP's question is not reproducible):
Y.columns <- c("cyl")
X.columns <- c("disp","hp","drat")
Y.string <- paste(Y.columns, collapse='+')
X.string <- paste(X.columns, collapse='+')
library(dplyr)
library(rlang)
mtcars %>%
mutate(Y = UQ(parse_quosure(Y.string)),
X = UQ(parse_quosure(X.string))) %>%
select(Y,X)
或带有 !!
:
mtcars %>%
mutate(Y = !!parse_quosure(Y.string),
X = !!parse_quosure(X.string)) %>%
select(Y,X)
结果:
Y X
1 6 273.90
2 6 273.90
3 4 204.85
4 6 371.08
5 8 538.15
6 6 332.76
7 8 608.21
8 4 212.39
9 4 239.72
10 6 294.52
...
注意:
mutate _
有现在已弃用,所以我认为使用 quosure
和 UQ
的tidyeval是新的解决方法。
mutate_
has now deprecated, so I think tidyeval with quosure
's and UQ
is the new way to go.
这篇关于dplyr使用列名称的字符向量进行变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文