简体   繁体   English

在R中向量化'deparse(substitute(d))'吗?

[英]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 ? 我想知道为什么,当使用下面的命令运行以下内容时: bb(d = c(dnorm, dcauchy) )我收到一条错误消息: object 'c(dnorm, dcauchy)' not found

PS But as I show below, the function has no problem with bb(d = c(dnorm)) . 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

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. c()函数用于组合向量,而不是魔术的“数组”函数或其他任何函数。 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. 如果您具有简单原子类型的集合,则可以将它们与c()结合在一起,但是对于函数之类的更复杂的对象,则需要将它们收集在列表中,而不是向量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R:向量化解析(替代(x)) - R: Vectorize deparse(substitute(x)) R's deparse(替代(var))的对面? - Opposite of R's deparse(substitute(var))? 在lapply?deparse(substitute(x))? - deparse(substitute(x)) in lapply? deparse(substitute()) 与 lapply - deparse(substitute()) with lapply 对多个字符串使用deparse(substitute) - Using deparse(substitute) for several strings 如何使用assign(deparse(substitute(df)))将相同的函数应用于多个数据帧以覆盖输入变量? [R] - How to apply the same functions to multiple data frames to overwrite input variables using assign(deparse(substitute(df)))? [R] R 用户定义的保存加载函数| 使用 deparse(substitute) 将变量名作为参数传递 - R user-defined save load functions | Passing variable names as arguments using deparse(substitute) R:当函数调用为3点时,无法使用Deparse和Replace完全捕获所有参数 - R: cannot fully capture all arguments using deparse and substitute when function call is 3 dots 在R中,我如何定义一个等效于`deparse(substitute(x))`的函数? - In R, how do I define a function which is equivalent to `deparse(substitute(x))`? 在 R 中匹配 function:match.fun vs deparse(substitute()) vs “直接”提供 function - Matching function in R: match.fun vs deparse(substitute()) vs supplying function "directly"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM