Converting a list of lists of vectors into a list of matrices - R

Asked

Viewed 155 times

-1

I’m working on an environmental model that returns a list of vectors. Each list corresponds to a point in space, and each vector is a time series of data for different variables. I’m trying to extract each vector from each list to create matrices, one for each variable.

The structure I’m trying to convert looks like this:

t <- list(list("r" = c(1,2,3), "e" = c(4,5,6), "t" = c(7,8,9)),
          list("r" = c(11,12,13), "e" = c(14,15,16), "t" = c(17,18,19)))

I want it to become that:

t0 <- list("r" = do.call(rbind, list(c(1,2,3), c(11,12,13))),
           "e" = do.call(rbind, list(c(4,5,6), c(14,15,16))),
           "t" = do.call(rbind, list(c(7,8,9), c(17,18,19))))

How could I do this conversion without specifying the names of the columns, but still keeping them to access using the operator $?

1 answer

3

If the structure of all list elements is the same, i.e., they all have the same names and lengths, you can put them in the same arrangement and then separate them by the number of variables and elements in each vector. The process does not preserve the names, but just retrieve them at the end. If you run your model several times, put everything in a function to facilitate:

arruma.lista <- function(lista) {
  n.var <- length(lista[[1]])  # número de variáveis:
  n.elmt <- length(lista[[1]][[1]])  # número de elementos em cada variável
  lista.a <- matrix(unlist(lista), ncol = length(lista))  # matriz geral
  lista.a <- split(lista.a, rep(seq(n.var), each = n.elmt))  # separa por variável
  lista.a <- lapply(lista.a, matrix, nrow = length(lista), byrow = TRUE)  # converte para matriz
  names(lista.a) <- names(lista[[1]])  # recupera os nomes
  return(lista.a)
}

t2 <- arruma.lista(t)

> t2$e
    [,1] [,2] [,3]
[1,]    4    5    6
[2,]   14   15   16

Browser other questions tagged

You are not signed in. Login or sign up in order to post.