【问题标题】:Nested operation in R. Is there a more elegant way?R中的嵌套操作。有没有更优雅的方法?
【发布时间】:2017-01-10 17:29:16
【问题描述】:

我在 R 中进行这种递归操作(卷积),只需像俄罗斯娃娃一样将一个函数嵌套到另一个函数中。问题是是否有更优雅的方式来做到这一点。

首先肯定有更好的方法来设置以下输入向量:

ones =   c(1, 1, 1, 1, 1, 1)
twos =   c(1, 0, 1, 0, 1, 0)
threes = c(1, 0, 0, 1, 0, 0)
fours =  c(1, 0, 0, 0, 1, 0)

实际的行是:

round(convolve(convolve(convolve(ones, rev(twos), type="open"), rev(threes), type="open"), rev(fours), type="open")) [1] 1 1 2 3 5 6 6 8 8 8 6 6 5 3 2 1 1 0 0 0 0

【问题讨论】:

  • 在基础R中有Reduce(),在purrr中有reduce()
  • @RichScriven 现在更正了错字。对此感到抱歉。

标签: r nested


【解决方案1】:
library(purrr)
data <- list(ones, twos, threes, fours)
round(reduce(data, ~ convolve(.x, rev(.y), type = "open")))

您可以使用 base Reduce() 实现相同的效果:

round(Reduce(f = function(x, y) convolve(x, rev(y), type = "open"), x = data))

【讨论】:

    【解决方案2】:

    我不能说是否有更好的方法来设置函数,但是 R 中的 dplyr 包可以让语法写得更好一点:

    library(dplyr)
    ones %>% 
      convolve(rev(twos), type = "open") %>%
      convolve(rev(threes), type = "open") %>%
      convolve(rev(fours), type = "open") %>%
      round
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2015-10-10
    相关资源
    最近更新 更多