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))
But I think my get_expr
function is some kind of hack. Logically, the evaluation should not be necessary.
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).
I found another way via parse(text = deparse(val))
, but this is even more a bad hack...
call('expression', val)
looks much better and works for me and does not even needenquote
.enquote(val)[[2]]
does not work for me, becauseas.expression(enquote(val)[[2]])
returnsexpression(1, 2)
(and a evaluation of this results in2
). – Zygotene