1TonDan
1TonDan

Reputation: 95

r - How to combine multiple lists of lists into a dataframe

I am trying to combine 2 lists of lists that are of unequal length into a data frame.

I am starting with a list containing 2 matrices.

mtx_a <- matrix(data = c(1:24), nrow = 4)
mtx_b <- matrix(data = c(25:36), nrow = 3)
row.names(mtx_a) <- c("A", "B", "C", "D")
row.names(mtx_b) <- c("A", "B", "C")
colnames(mtx_a) <- c("V1", "V2", "W1", "W2", "X1", "X2")
colnames(mtx_b) <- c("Y1", "Y2", "Z1", "Z2")
mtx_list <- list(mtx_a, mtx_b)
names(mtx_list) <- c("mtx_a", "mtx_b")
mtx_list

I have extracted a specific row based on rowname to examine.

mtx_list <- lapply(mtx_list, function(mtx_list){
  mtx_list[row.names(mtx_list) %in% c("A"),]})

Next I extracted specific columns based on their index. (Alternating columns are equivalent to condition 1 and 2).

cond_1 <- lapply(lapply(mtx_list, function(mtx_list) {
  mtx_list[c(T,F)]}), unname)
cond_2 <- lapply(lapply(mtx_list, function(mtx_list) {
  mtx_list[c(F,T)]}), unname)

I am trying to generate a data frame that looks like this:

        cond_1   cond_2 
mtx_a   1        5
mtx_a   9        13
mtx_a   17       21
mtx_b   25       28
mtx_b   31       34

I have tried the following but have not have any success:

list(cond_1, cond_2)
library(plyr)
ldply(c(cond_1, cond_2))

Upvotes: 2

Views: 6560

Answers (3)

d.b
d.b

Reputation: 32558

You can use Map to cbind respective list elements.

do.call(rbind, Map(cbind, cond_1, cond_2))
#     [,1] [,2]
#[1,]    1    5
#[2,]    9   13
#[3,]   17   21
#[4,]   25   28
#[5,]   31   34

A little more work can give you slightly better result

data.frame(mtx = unlist(lapply(1:length(cond_1),
                               function(i)
                                   rep(names(cond_1)[i], length(cond_1[[i]])))),
    do.call(rbind, Map(cbind, cond_1, cond_2)))
#    mtx X1 X2
#1 mtx_a  1  5
#2 mtx_a  9 13
#3 mtx_a 17 21
#4 mtx_b 25 28
#5 mtx_b 31 34

Upvotes: 3

thelatemail
thelatemail

Reputation: 93938

Extract all the "A" rows first, then just feed into a 2-column matrix:

matrix(unlist(lapply(mtx_list, `[`, "A", )), ncol=2, byrow=TRUE)
#     [,1] [,2]
#[1,]    1    5
#[2,]    9   13
#[3,]   17   21
#[4,]   25   28
#[5,]   31   34

That can be wrapped in data.frame() if need be.

Upvotes: 4

lmo
lmo

Reputation: 38520

Here is an alternative using sapply. I wrapped it in a function for easier repeated use.

getter <- function(rowName) {
  # loop through matrices in list, pull out rows that match name
  temp <- unlist(sapply(mtx_list, function(x) x[rowName,]), use.names=FALSE)
  # return data.frame with alternating values
  data.frame(var1=temp[c(TRUE, FALSE)], var2=temp[c(FALSE, TRUE)])
}

getter("A")
  var1 var2
1    1    5
2    9   13
3   17   21
4   25   28
5   31   34

Note that it is necessary that all matrices in the list contain the row name for this function to work.

Upvotes: 2

Related Questions