This is a question that relates to my previous two questions: https://stackoverflow.com/questions/37996470/how-to-map-a-function-recursively-through-nested-lists-in-r, and https://stackoverflow.com/questions/37906958/how-to-combine-rapply-and-mapply-or-how-to-use-mapply-map-recursively , except now I am asking for more bells and whistles...
So I have multiple nested lists:
A = list(list(list(c(1,2,3), c(2,3,4)),list(c(1,2,3),c(2,3,4))), list(c(4,3,2), c(3,2,1)))
B = list(list(list(c(1,2,3), c(2,3,4)),list(c(1,2,3),c(2,3,4))), list(c(4,3,2), c(3,2,1)))
And I'd like to apply a function recursively to the corresponding lists in A
and B
. If the function only takes sublists of A
and B
as arguments, according to excellent answers to my previous questions, it can be done like this:
recursive <- function(fun, x, y) {
if(is.atomic(x) && is.atomic(y)) {
match.fun(fun)(x, y)
} else {
Map(recursive, x, y, MoreArgs=list(fun=fun))
}
}
Now I am wondering how can I add more arguments that are constant across different sublists of A
and B
? For instance, my function could be
formula = function(sublistA, sublistB, arg1, arg2){return(arg1*sublistA+arg2*sublistB)}
I think the recursive function possibly adapted from above might look like
recursive <- function(fun, x, y, a, b) {
if(is.list(a) && is.list(b)){
}...
}
And can we make the recursive function flexible regarding the number of structured lists like x
and y
and the number of constants (could be matrices, vectors, lists, so long as not included in the recursion) like a
and b
?
Any guidance is greatly appreciated.