【问题标题】:Returning a closure using vapply使用 vapply 返回闭包
【发布时间】:2014-08-19 13:04:31
【问题描述】:

如果我有一个函数发生器,即

prepend_text = function(text) {
  function(x) {
    paste(text, x)
  }
}

是否可以使用 vapply 返回结果函数的向量?我不知道如何为 vapply 指定返回类型为 closure

vapply(c('one', 'two', 'three'), FUN.VALUE=???, prepend_text)

使用任何其他值 character(1) 等。产量

# Error in vapply(c('one', 'two', 'three'),  :
#   values must be type 'character',
#  but FUN(X[[1]]) result is type 'closure'

我认为这可能是不可能的,使用sapply 实际上会返回我想要的,所以这个问题主要是学术性的。

我要查找的输出也包含每个函数的名称,因此简单的lapply 调用也不起作用。

预期输出等价于

c(one=prepend_text('one'), two=prepend_text('two'), three=prepend_text('three'))

【问题讨论】:

    标签: r


    【解决方案1】:

    vapply 不会返回函数,但lapply 会。如果要添加名称,可以在输入对象上设置:

    x <- c('one', 'two', 'three')
    names(x) <- x
    lapply(x, prepend_text)
    

    【讨论】:

    • 我不知道 lapply 在命名向量输入上保留名称,感谢 winston 的提示和回答!
    【解决方案2】:

    我建议在这些情况下使用 lapply。

    你可以试试这个吗?

    lapply(list('one', 'two', 'three'), prepend_text)
    

    祝你好运!

    【讨论】:

    • 我应该指定我还希望将名称添加到输出中,我稍微修改了问题。
    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 2017-09-16
    • 2020-01-22
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2014-10-25
    相关资源
    最近更新 更多