[英]Vectorizing 'deparse(substitute(d))' in R?
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
? 我想知道为什么,当使用下面的命令运行以下内容时:
bb(d = c(dnorm, dcauchy) )
我收到一条错误消息: object 'c(dnorm, dcauchy)' not found
?
PS But as I show below, the function has no problem with bb(d = c(dnorm))
. PS但是如下面所示,该函数对于
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)
The c()
function is meant to combine vectors, it's not a magic "array" function or anything. c()
函数用于组合向量,而不是魔术的“数组”函数或其他任何函数。 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. 如果您具有简单原子类型的集合,则可以将它们与
c()
结合在一起,但是对于函数之类的更复杂的对象,则需要将它们收集在列表中,而不是向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.