Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested operation in R. Is there a more elegant way?

Tags:

r

nested

I am carrying on this recursive operation (convolution) in R by just nesting one function into the other like a Russian doll. The question is whether there is a more elegant way of doing this.

To begin with there is surely a better way to set up the following input vectors:

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)

The actual line is:

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

like image 711
Antoni Parellada Avatar asked Nov 22 '25 08:11

Antoni Parellada


1 Answers

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

You can achieve the same with base Reduce():

round(Reduce(f = function(x, y) convolve(x, rev(y), type = "open"), x = data))
like image 56
Aurèle Avatar answered Nov 24 '25 23:11

Aurèle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!