Nneka
Nneka

Reputation: 1860

Recursively Apply a Function with multiple arguments to a List in R

I have a nested list and want to apply the same functions to multiple levels of this list. The functions are quite complex and require multiple arguments.

Here i have found how rapply is used and though it would be useful to me. Unfortunately rapply only take functions of a single argument.

Here is an little example in R :

nested list:

x=list(1,list(2,3),4,list(5,list(6,7)))

functions with multiple arguments:

doAddition <- function(listIterator,
                       list,
                       add){
  
  item <- list[listIterator]]
  out <- item + add
  return(out)
  
}

I would use this function of the first level of my list such as:

result <- lapply(seq_along(x), FUN = doAddition,
                 list = x, 
                 add = factor)

How can i use the same functions for all my lists levels? Is there an alternative to rapply that accepts multiple arguments?

Upvotes: 0

Views: 212

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

You generally wouldn’t iterate over indices, you’d iterate over elements. Once you do that, your code is directly translatable to rapply:

rapply(x, `+`, ... = factor)

This unlists the results. If you want to preserve the nested list structure, pass how = 'list' to rapply.

Note that this isn’t using your custom doAddition function since, once you iterate over elements, that function isn’t necessary. If your actual function is more complex the same applies: pass an element, not an index.

Upvotes: 2

Related Questions