Convert string to non-string input for function

混江龙づ霸主 提交于 2021-02-07 19:57:31

问题


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))   

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'

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


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


回答1:


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 is equivalent to parse in base R:

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

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)


来源:https://stackoverflow.com/questions/47225650/convert-string-to-non-string-input-for-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!