I wonder if there is a more efficient way of applying a function over every two consecutive elements of a list. This question got me thinking, and the solution I posted for the user came from here.
I think it is decent enough to use Map/mapply
with somelist[-length(somelist)]
and somelist[-1]
as the arguments to a function(x, y)
call, but is there any direct approach, maybe implemented in one of the bigger/newer packages?
Consider this example (stolen from the aforementioned question):
I've got a list of three matrices:
set.seed(1)
matlist <- list(M1 = matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
M2 = matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2),
M3 = matrix(sample(1:10, 4, replace = T), nrow = 2, ncol = 2)
)
and now I want to calculate M1+M2
and M2+M3
. The mentioned approach would be
Map(`+`, matlist[-3], matlist[-1])
[[1]]
[,1] [,2]
[1,] 5 11
[2,] 11 15
[[2]]
[,1] [,2]
[1,] 12 13
[2,] 5 18
Is there any variant of the apply
family to which I would just feed
xapply(matlist, `+`)
I know I could just write that myself as a little helper, like
xapply <- function(x, FUN){
Map(FUN, x[-length(x)], x[-1])
}
but as far as I understood this classic, sapply/lapply
and so on gain their performance advantage over for
loops by utilizing C
code, therefore the xapply
function above would be convenience only, not boosting performance.