【问题标题】:Why can't I assign a function with ifelse in R?为什么我不能在 R 中使用 ifelse 分配函数?
【发布时间】:2014-03-01 22:01:20
【问题描述】:

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

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

如果condFALSE,错误看起来是等价的,R 抱怨一个

attempt to replicate an object of type 'closure'

如何将两个函数之一分配给一个变量以及这里发生了什么?

【问题讨论】:

标签: r functional-programming


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我会选择switch——在许多教程中都有示例说明如何使用switch 获取不同的函数并将它们应用于输入。
    • ...或者只使用my.func &lt;- if(cond) sqrt else identity。无需滥用ifelse
    • 如果需要,如何将其矢量化?
    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2014-12-05
    • 2013-12-22
    • 1970-01-01
    • 2017-12-22
    相关资源
    最近更新 更多