且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将字符串转换为函数的非字符串输入

更新时间:2023-02-03 08:46:26

你漏掉了表达式中的c(),你还需要在你的表达式里面eval子集:

You missed the c() in your expression, and you also need to eval your expressions inside subset:

library(rlang)

x <- parse_expr("c(cyl:drat, vs:gear)")
subset(mtcars, select=eval(x))

parse_expr 等价于基础 R 中的 parse:

parse_expr is equivalent to parse in base R:

x2 = parse(text="c(cyl:drat, vs:gear)")
subset(mtcars, select=eval(x2))

您还可以在 dplyr 中将 parse_exprparse_exprsselect 一起使用,这是它的目的使用:

You can also use parse_expr or parse_exprs alongside select from dplyr, which is where it was intended to be used:

library(dplyr)

select(mtcars, !! x)

或用于拼接表达式列表:

or for splicing a list of expressions:

y = parse_exprs("cyl:drat; vs:gear")
select(mtcars, !!! y)