在 R 中,当我尝试通过 ifelse
分配函数时,出现以下错误:
> my.func <- ifelse(cond, sqrt, identity)
Error in rep(yes, length.out = length(ans)) :
attempt to replicate an object of type 'builtin'
如果 cond
为 FALSE
,则错误看起来相同,R 会提示
attempt to replicate an object of type 'closure'
我可以做什么来将两个函数之一分配给一个变量,这里发生了什么?
最佳答案
由于 ifelse
已向量化,并且不提供非向量化条件的特殊情况,因此参数将使用 rep(...)
进行复制。 rep(...)
对于闭包失败,例如示例中的情况。
解决方法是临时包装函数:
my.func <- ifelse(cond, c(sqrt), c(identity))[[1]]
关于r - 为什么我不能在 R 中使用 ifelse 分配函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21577818/