rnorouzian
rnorouzian

Reputation: 7517

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?

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

Upvotes: 0

Views: 263

Answers (1)

MrFlick
MrFlick

Reputation: 206197

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.

Upvotes: 2

Related Questions