从一个值获得一个R表达式(simlar to enquote) [英] Getting an R expression from a value (simlar to enquote)

查看:260
本文介绍了从一个值获得一个R表达式(simlar to enquote)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个价值 x 这是一些(未知)类型(特别是:标量,向量或列表)。我想得到表达这个值的R表达式。如果 x == 1 则该函数应该简单地返回 expression(1)。对于 x == c(1,2))此函数应返回表达式(c(1,2)) enquote 函数与我想要的功能非常接近,但不完全相同。



通过一些玩,我发现以下解决方案到我的问题:

  get_expr < -  function(val){
tmp_expr < - enquote(val)
tmp_expr [1]< - quote(expression())
return (1)
get_expr(c(1,2))#返回表达式(c(1,2))
get_expr(list(x = 1))#返回表达式(list(x = 1))

但我认为我的 get_expr 功能是某种黑客。在逻辑上,评估不是必要的。



有没有一些更优雅的方式来做到这一点?据我看到,替代对我来说并不适用,因为我的 get_expr 函数的参数可能是评估结果(和 substitute(eval(expr))不做评估)



我发现另一种方式是通过 parse(text = deparse(val)),但这更是一个坏的黑客...

解决方案

as.expression(list(...))似乎这样做:

 > get_expr<  -  function(val)as.expression(list(val))
> str(get_expr(1))
表达式(1)
> str(get_expr(c(1,2)))
表达式(c(1,2))
> str(get_expr(list(x = 1)))
expression(list(x = 1))
> val< - list(x = 1,y = 2)
> str(get_expr(val))
表达式(list(x = 1,y = 2))


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

解决方案

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

> 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表达式(simlar to enquote)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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