r - 在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
解决方案
尝试这种替代方法,将函数直接传递给函数
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()
,但对于更复杂的对象(如函数),您需要将它们收集在列表中,而不是向量中。
推荐阅读
- reactjs - React Hooks 从 react-redux 更新 props
- amazon-web-services - AWS 是否保证我的 lambda 函数会 100% 触发?
- excel - Excel 表单:以 PDF 格式发布时变形的对象
- magento - 设置时 magento 2 索引错误的产品平面数据:升级或索引器:重置
- r - 如何让用户在下载文件之前多次输入表单?
- sorting - 计算特征矩阵沿指定轴的中值
- python - Pandas 按名称和日期合并(多列)
- r - 在数据集模拟中循环
- c# - 如何在 C# 中显示来自 gmap 的地址?
- node.js - 如何为 Node.js 设置 Google 翻译 API?