R有许多强制手段:as.logical
,as.integer
,as.data.frame
等。
但是,使用这些函数需要事先知道(“在编译时”)目标类(logical
,integer
,data.frame
等。)
但是在我正在处理的问题中,我需要强制expr1
到class(expr2)
,其中expr1
和expr2
是任意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))
形式的表达式来解决我真正感兴趣的用例。我认为这是一个合理的假设,但如果事实证明不成立,我认为我会拼出所有这些。