为什么我不能在R中分配带ifelse的函数?

时间:2022-01-10 22:04:54

In R, when I try to assign a function via ifelse, I get the following error:

在R中,当我尝试通过ifelse分配函数时,我收到以下错误:

> my.func <- ifelse(cond, sqrt, identity)
Error in rep(yes, length.out = length(ans)) : 
  attempt to replicate an object of type 'builtin'

If cond is FALSE, the error looks equivalent, R complains about an

如果cond为FALSE,则错误看起来相同,R抱怨一个

attempt to replicate an object of type 'closure'

What can I do to assign one of two functions to a variable and what is going on here?

如何将两个函数中的一个赋值给变量以及此处发生了什么?

2 个解决方案

#1


5  

Because ifelse is vectorized and does not provide special cases for non-vectorized conditions, the arguments are replicated with rep(...). rep(...) fails for closures such as in the example though.

因为ifelse是矢量化的,并且不为非矢量化条件提供特殊情况,所以使用rep(...)复制参数。 rep(...)无法用于闭包,例如在示例中。

A workaround would be to temprarily wrap the functions:

解决方法是临时包装函数:

my.func <- ifelse(cond, c(sqrt), c(identity))[[1]]

#2


1  

@Joshua Ulrich's comment is a proper answer. The correct way to accomplish conditional function assignment is a classic if...else rather than the vectorized ifelse method:

@Joshua Ulrich的评论是一个正确的答案。完成条件函数赋值的正确方法是经典的if ... else而不是vectorized ifelse方法:

my.func <- if (cond) sqrt else identity

#1


5  

Because ifelse is vectorized and does not provide special cases for non-vectorized conditions, the arguments are replicated with rep(...). rep(...) fails for closures such as in the example though.

因为ifelse是矢量化的,并且不为非矢量化条件提供特殊情况,所以使用rep(...)复制参数。 rep(...)无法用于闭包,例如在示例中。

A workaround would be to temprarily wrap the functions:

解决方法是临时包装函数:

my.func <- ifelse(cond, c(sqrt), c(identity))[[1]]

#2


1  

@Joshua Ulrich's comment is a proper answer. The correct way to accomplish conditional function assignment is a classic if...else rather than the vectorized ifelse method:

@Joshua Ulrich的评论是一个正确的答案。完成条件函数赋值的正确方法是经典的if ... else而不是vectorized ifelse方法:

my.func <- if (cond) sqrt else identity