Vectorizing 'deparse(substitute(d))' in R?

旧巷老猫 提交于 2021-02-08 09:53:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!