Search code examples
rlapplysapply

optimize the loop to combine items from a list using lapply or sapply in R


I have as an example the following list:

>lista 
[[1]]
      row col   
[1, ]   4 453
[2, ]   5 453

[[2]]
     row col
[1, ] 26 264
[2, ] 26 265
[3, ] 26 266
[4, ] 27 265
[5, ] 27 266

[[3]]
     row col
[1,]  35 364
[1,]  35 365
[2,]  35 366

the goal is to combine the elements of the list, in the form: list[[1]] with list[[2]], list [[1]] with list[[3]] successively (I have a list in the order of five thousand items or more)

The expected result is:

[[1]]
      row col   
[1, ]   4 453
[2, ]   5 453
[3, ]  26 264
[4, ]  26 265
[5, ]  26 266
[6, ]  27 265
[7, ]  27 266

[[2]]
     row col    
[1, ]  4 453
[2, ]  5 453
[3, ] 35 364
[4, ] 35 365
[5, ] 35 366
.
.
.

So, I have the following function that works fine, but since the number of items in the list is very large, this process takes a long time.

rows_bind <- function(all_GG){
  nn_GG <- length(all_GG)
  lista_analizar <- list()
  cont <- 1
  repeat {
    lista_analizar[[cont]] <- rbind(all_GG[[1]], all_GG[[cont+1]])
    cont = cont + 1
    if (cont == nn_GG){
      break
    }
  }
  return(lista_analizar)
}

My question is: how can I optimize this function? to use it inside a function like lapply() or sapply(). Or better yet use parSapply() or parLapply()


Solution

  • Growing objects in a loop are mostly inefficient. Try with Map/lapply :

    result <- Map(rbind, lista[1], lista[-1])
    

    Using lapply you can write this as :

    result <- lapply(lista[-1], function(x) rbind(lista[[1]], x))