从值获取R表达式(类似于enquote) [英] Getting an R expression from a value (similar to enquote)
问题描述
假设我有一个值x
,它是某些(未知)类型(尤其是:标量,向量或列表).我想获得代表该值的R表达式.如果为x == 1
,则此函数应简单地返回expression(1)
.对于x == c(1,2))
,此函数应返回expression(c(1,2))
. enquote
函数与我想要的功能非常接近,但不完全相同.
Assume I have a value x
which is of some (unknown) type (especially: scalar, vector or list). I would like to get the R expression representing this value. If x == 1
then this function should simply return expression(1)
. For x == c(1,2))
this function should return expression(c(1,2))
. The enquote
function is quite near to that what I want, but not exactly.
通过玩耍,我找到了解决问题的以下解决方案":
By some playing around I found the following "solution" to my problem:
get_expr <- function(val) {
tmp_expr <- enquote(val)
tmp_expr[1] <- quote(expression())
return(eval(tmp_expr))
}
get_expr(1) # returns expression(1)
get_expr(c(1, 2)) # returns expression(c(1, 2))
get_expr(list(x = 1)) # returns expression(list(x = 1))
但是我认为我的get_expr
函数是某种hack.从逻辑上讲,不需要评估.
But I think my get_expr
function is some kind of hack. Logically, the evaluation should not be necessary.
是否有一些更优雅的方法可以做到这一点?据我所知,substitute
对我来说并不真正有用,因为我的get_expr
函数的参数可能是求值的结果(而substitute(eval(expr))
并不求值).
Is there some more elegant way to do this? As far as I see, substitute
does not really work for me, because the parameter of my get_expr
function may be the result of an evaluation (and substitute(eval(expr))
does not do the evaluation).
我通过parse(text = deparse(val))
找到了另一种方法,但这更是一个糟糕的hack ...
I found another way via parse(text = deparse(val))
, but this is even more a bad hack...
推荐答案
as.expression(list(...))
似乎可以做到:
> get_expr <- function(val) as.expression(list(val))
> str(get_expr(1))
expression(1)
> str(get_expr(c(1, 2)))
expression(c(1, 2))
> str(get_expr(list(x=1)))
expression(list(x = 1))
> val <- list(x=1, y=2)
> str(get_expr(val))
expression(list(x = 1, y = 2))
这篇关于从值获取R表达式(类似于enquote)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!