将字符串转换为函数的非字符串输入 [英] Convert string to non-string input for function

查看:77
本文介绍了将字符串转换为函数的非字符串输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何存储一个字符串(例如,列范围 "cyl:drat, vs:gear")以便我可以在它应该不的函数中使用它em> 被解释为字符串?

How can I store a string (e.g., the column range "cyl:drat, vs:gear") so that I can use it in a function where it should not be interpreted as character string?

例如,我想执行以下命令:

For example, I would like to execute the following command:

subset(mtcars, select=c(disp:drat, vs:gear))   

但是将select的内容赋值给一个变量x:

But assign the content for select to a variable x:

x <- as.name("cyl:drat, vs:gear")
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'symbol'

library(rlang)
x <- quo(!! sym("cyl:drat, vs:gear"))
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'language'

x <- parse_expr("cyl:drat, vs:gear")
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'language'

分配 x <-"cyl" 有效,但 x <-"cyl:drat" 同样失败.

Assigning x <-"cyl" works, but x <-"cyl:drat" similarly fails.

关于 x 应该具有什么格式的提示已经是一个受欢迎的开始.

Hints as to what format x should have would already be a welcome start.

推荐答案

你漏掉了表达式中的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)

这篇关于将字符串转换为函数的非字符串输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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