Getting R expression from value (similar to enquote)

Suppose I have an x value that has some (unknown) type (especially a scalar, vector, or list). I would like to get an expression R 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 enquote pretty close to what I want, but not exactly.

Through some games, I found the following β€œsolution” for 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 a kind of hack. Logically, an assessment is not needed.

Is there an even more elegant way to do this? As far as I know, substitute doesn't actually work for me, because the parameter of my get_expr function may be the result of the evaluation (and substitute(eval(expr)) does not perform the evaluation).

I found another way through parse(text = deparse(val)) , but this is an even worse hack ...

+6
source share
2 answers

as.expression(list(...)) seems to do this:

 > 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)) 
+6
source

You can use substitute() , and you just need to name it differently:

 express <- function(e) substitute(expression(x), env = list(x=e)) v1 <- c(1, 2) express(v1) # expression(c(1, 2)) v2 <- list(a = 1, b = 2) express(v2) # expression(list(a = 1, b = 2)) 
+2
source

Source: https://habr.com/ru/post/983225/


All Articles