如何将表达式强制转换为仅在运行时才知道的类?

时间:2016-10-13 13:00:38

标签: r

R有许多强制手段:as.logicalas.integeras.data.frame等。

但是,使用这些函数需要事先知道(“在编译时”)目标类(logicalintegerdata.frame等。)

但是在我正在处理的问题中,我需要强制expr1class(expr2),其中expr1expr2是任意R表达式,其类别未知直到运行时。

我不认为R对这个确切的用例有任何内置支持,但我希望它能够将任意表达式强制转换为任意类。 IOW,我希望R已经有类似coerce(expr, a.class) 1 的东西。

我知道我可以滚动自己coerce,就像这样:

coerce <- function (expr, a.class) {
  ## coerce expr to a.class
  switch(a.class,
         character = as.character(expr),
           logical = as.logical(expr),
           integer = as.integer(expr),
           numeric = as.numeric(expr),

           # yadda-yadda-yadda

                     stop(sprintf('unsupported class: %s', a.class)))
}

> coerce(5, "foo")
[1] "5"

另外,我知道人们也可以诉诸于此:

coerce2 <- function (expr, a.class) {
  ## coerce expr to a.class; take 2
  rcode <- sprintf("as.%s(expr)", a.class)
  tryCatch(eval(parse(text=rcode)),
           error = function (condtion) {
                     stop(sprintf('unsupported class: %s', a.class))
                   })
}

> coerce2(5, data.frame())
  x
1 5

...但我希望R已经支持了比这更强大和更强大的东西。

1我的假设是我可以使用coerce(expr1, class(expr2))形式的表达式来解决我真正感兴趣的用例。我认为这是一个合理的假设,但如果事实证明不成立,我认为我会拼出所有这些。

0 个答案:

没有答案
相关问题