B_Miner
B_Miner

Reputation: 1832

Extract elements from a vector within lists

I have a list of length 30000 and each list element contains one vector of length 6.

Example (with a length of just 2):

trainLists <- list(c(1,2,3,4,5,6),c(7,8,9,10,11,12))

I want to "flatten" these lists into a dataframe and create 6 factors (one corresponding to each of the elements in the vectors in the list).

Thus, the result would be:

enter image description here

I can accomplish this with a loop such as

for (i in 1:length(trainLists){
   factor1 [i] <- trainLists[[i]][1]
   factor2 [i] <- trainLists[[i]][2]
   factor3 [i] <- trainLists[[i]][3]
   factor4 [i] <- trainLists[[i]][4]
   factor5 [i] <- trainLists[[i]][5]
   factor6 [i] <- trainLists[[i]][6]
}

but it is horribly slow. How best to accomplish this?

Upvotes: 1

Views: 156

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

As noted in the comments, most of what you want to do is achieved with a simple do.call(rbind, ...), like this:

> trainLists <- list(c(1,2,3,4,5,6),c(7,8,9,10,11,12))
> trainLists
[[1]]
[1] 1 2 3 4 5 6

[[2]]
[1]  7  8  9 10 11 12

> do.call(rbind, trainLists)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    7    8    9   10   11   12

Taking things a few steps forward, you can do something like this:

cbind(example = seq_along(trainLists), 
      setNames(data.frame(do.call(rbind, trainLists)),
               paste0("Factor_", sequence(
                 max(sapply(trainLists, length))))))
#   example Factor_1 Factor_2 Factor_3 Factor_4 Factor_5 Factor_6
# 1       1        1        2        3        4        5        6
# 2       2        7        8        9       10       11       12

Upvotes: 0

Related Questions