在R中嵌套操作。有更优雅的方式吗?

时间:2017-01-10 17:29:16

标签: r nested

我正在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

2 个答案:

答案 0 :(得分:5)

library(purrr)
data <- list(ones, twos, threes, fours)
round(reduce(data, ~ convolve(.x, rev(.y), type = "open")))

您可以使用基座Reduce()实现相同的目标:

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

答案 1 :(得分:1)

我不能说是否有更好的方法来设置该功能,但R中的dplyr包使得编写语法更加可能:

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