我正在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)
Run Code Online (Sandbox Code Playgroud)
实际的是:
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
library(purrr)
data <- list(ones, twos, threes, fours)
round(reduce(data, ~ convolve(.x, rev(.y), type = "open")))
Run Code Online (Sandbox Code Playgroud)
你可以用base实现同样的目标Reduce():
round(Reduce(f = function(x, y) convolve(x, rev(y), type = "open"), x = data))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |