qua*_*gar 7 functional-programming r
在R中,当我尝试通过via分配函数时ifelse,我收到以下错误:
> my.func <- ifelse(cond, sqrt, identity)
Error in rep(yes, length.out = length(ans)) :
attempt to replicate an object of type 'builtin'
Run Code Online (Sandbox Code Playgroud)
如果cond是FALSE,错误看起来相当,R抱怨一个
attempt to replicate an object of type 'closure'
Run Code Online (Sandbox Code Playgroud)
如何将两个函数中的一个分配给变量以及此处发生了什么?
因为ifelse是向量化的并且没有为非向量化条件提供特殊情况,所以参数被复制rep(...). rep(...)但是在例如示例中的闭包失败了.
解决方法是临时包装函数:
my.func <- ifelse(cond, c(sqrt), c(identity))[[1]]
Run Code Online (Sandbox Code Playgroud)