Search code examples
rlapply

Optimize using multiple consecutive lapply functions?


I am trying to write a function where I apply the same set of functions to a list.

Currently I got this approach to work but it seems very clumsy and I wonder if and how it can be improved:

t1 <- lapply(mylist,
             FUN = myfunc1)

t2 <- lapply(t1,
             FUN = as.data.frame)

t3 <- lapply(t2,
             FUN = t)

t4 <- lapply(t3,
             FUN = myfunc2)

So I first need to extract objects from a list, turn them into data frames, then transpose them and then finally apply the real function.


Solution

  • 1) We can use Reduce on a list of functions:

    L <- as.list(1:3)
    Reduce(lapply, list(sqrt, exp), init = L)
    

    2) Also

    lapply(L, \(x) exp(sqrt(x)))
    

    3) or using magrittr

    library(magrittr)
    
    lapply(L, . %>% sqrt %>% exp)
    

    4) with purrr. In this case reverse the order of the functions.

    library(purrr)
    
    map(L,  compose(exp, sqrt))
    

    5) Using Compose from functional is similar to (4) except for the order of functions.

    library(functional)
    
    lapply(L, Compose(sqrt, exp))