Leonardo Lanchas
Leonardo Lanchas

Reputation: 1668

R - Replace nested for - Nested lists

I build a list of lists in R and the only way I got it to work is with nested fors. The problem is that they take up to 4 seconds to run therefore it's extreme slow. This is how I build them:

tt = vector("list", length(dp$id))

for (idx in seq_along(dp$id)) {
   pos       = dp$id[idx]
   position  = dp[id == pos]$pdim
   tt[[idx]] = list(
      a = unbox(pos),
      b = list()
   )
   tmp = positionData[positionId == position]
   tls = vector("list", nrow(tmp))
   if (nrow(tmp)) {
      for (row in 1:nrow(tmp)) {
         tls[[row]] = list(
            c = unbox(tmp[row]$d),
            d = unbox(tmp[row]$c)
         )
      }
      tt[[idx]]$b = tls
   }
}

Is there a way to replace both for's to build the lists faster?

EDIT: sample data

dp = data.table(id =c(5632,5633, 5634, 5635, 5636), pdim = c(2103, 2048, 2093, 2069, 2086))

positionData = data.table(
positionId = c(2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048),

d = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0),
c = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))

Upvotes: 1

Views: 276

Answers (1)

Antonios
Antonios

Reputation: 1937

How about b for each tt sublist (5 in total) is a data.frame and not a list? If you can live with this you surely can avoid the second loop:

library(dplyr)
tt = list()
for (idx in seq_along(dp$id)) {
  pos = dp$id[idx]
  position= dp[id == pos]$pdim
  tt[[idx]] = list(a = pos,b = list())
  tmp = positionData[positionId == position]
  tls<-transmute(tmp,c=d,d=c)
  tt[[idx]]$b = tls
}

Upvotes: 1

Related Questions