首页 > 解决方案 > 在R中矢量化'deparse(substitute(d))'?

问题描述

我想知道为什么,在使用以下命令运行以下内容时:bb(d = c(dnorm, dcauchy) )我收到一条错误消息:object 'c(dnorm, dcauchy)' not found

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

标签: rfunction

解决方案


尝试这种替代方法,将函数直接传递给函数

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(),但对于更复杂的对象(如函数),您需要将它们收集在列表中,而不是向量中。


推荐阅读