问题
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. 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
回答1:
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. 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.
来源:https://stackoverflow.com/questions/50336517/vectorizing-deparsesubstituted-in-r