在R中向量化'deparse(substitute(d))'吗? [英] Vectorizing 'deparse(substitute(d))' in R?
问题描述
我想知道为什么,当使用以下命令运行以下代码时: bb(d = c(dnorm,dcauchy))
我收到一条错误消息: object'c(dnorm,dcauchy)'找不到
?
I'm wondering why, when running my below using: bb(d = c(dnorm, dcauchy) )
I get an error saying: object 'c(dnorm, dcauchy)' not found
?
P.S..但是,如下所示,该函数对于 bb(d = c(dnorm))
来说没有问题.
P.S. But as I show below, the function has no problem with bb(d = c(dnorm))
.
bb <- function(d){
d <- if(is.character(d)) d else deparse(substitute(d))
h <- numeric(length(d))
for(i in 1:length(d)){
h[i] <- get(d[i])(1) ## is there something about `get` that I'm missing?
}
h
}
# Two Examples of Use:
bb(d = dnorm) # Works OK
bb(d = c(dnorm, dcauchy) ) # Error: object 'c(dnorm, dcauchy)' not found
# But if you run:
bb(d = c("dnorm", "dcauchy"))# Works OK
推荐答案
在将函数直接传递给函数的情况下,尝试使用此替代方法
Try this alternative where you pass the functions directly to your function
bb <- function(d){
if (!is.list(d)) d <- list(d)
sapply(d, function(x) x(1))
}
bb(d = list(dnorm, dcauchy))
bb(d = dnorm)
c()
函数是用于组合向量的,它不是一个神奇的数组"函数,也不是任何东西.如果您具有简单原子类型的集合,则可以将它们与 c()
相连,但是对于函数之类的更复杂的对象,则需要将它们收集在列表中,而不是向量中.
The c()
function is meant to combine vectors, it's not a magic "array" function or anything. If you have collections of simple atomic types, you can join them with c()
, but for more complicated objects like functions, you need to collect those in a list, not a vector.
这篇关于在R中向量化'deparse(substitute(d))'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!