Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine dimensions of lists of lists into separate vectors

Here's an example of my data.

ll <- list(
  ll1 = list(Mi = 1:4,
       Mj = 10:13,
       dn = "l1"),
  ll2 = list(Mi = 5:8,
             Mj = 14:17,
             dn = "l2"))
> str(ll)
List of 2
 $ ll1:List of 3
  ..$ Mi: int [1:4] 1 2 3 4
  ..$ Mj: int [1:4] 10 11 12 13
  ..$ dn: chr "l1"
 $ ll2:List of 3
  ..$ Mi: int [1:4] 5 6 7 8
  ..$ Mj: int [1:4] 14 15 16 17
  ..$ dn: chr "l2"

I'm trying to combine each Mi, each Mj, and each dn together. So the final result will be 3 vectors: 1 combined Mi, 1 combined Mj, and 1 combined dn. I.e., the final result for Mi would be something like

> c(ll$ll1$Mi,ll$ll2$Mi)
[1] 1 2 3 4 5 6 7 8

Similar final results for Mj and dn. I'm wondering how to do this simply, preferably using something from tidyverse. The number of lists will vary and won't be 2 generally, which is why I don't think c is a great solution. I am guessing the map functions can work here, but I have not yet found a solution.

like image 698
drj3122 Avatar asked Dec 24 '22 04:12

drj3122


2 Answers

With pmap from purrr. pmap takes a list of inputs (in this case a list of two lists) and apply the c function to ll[[1]][[1]], ll[[2]][[1]], ... then ll[[1]][[2]], ll[[2]][[2]], ... and so on:

library(purrr)
pmap(ll, c)

Output:

$Mi
ll11 ll12 ll13 ll14 ll21 ll22 ll23 ll24 
   1    2    3    4    5    6    7    8 

$Mj
ll11 ll12 ll13 ll14 ll21 ll22 ll23 ll24 
  10   11   12   13   14   15   16   17 

$dn
 ll1  ll2 
"l1" "l2"

If we don't want to keep the vector names, we can use the use.names argument in c:

pmap(ll, c, use.names = FALSE)

Output:

$Mi
[1] 1 2 3 4 5 6 7 8

$Mj
[1] 10 11 12 13 14 15 16 17

$dn
[1] "l1" "l2"
like image 85
acylam Avatar answered Jan 13 '23 12:01

acylam


Another option would be to use purrr::transpose and unlist. This would give you a list of three vectors:

purrr::transpose(ll) %>% lapply(unlist)

$Mi
ll11 ll12 ll13 ll14 ll21 ll22 ll23 ll24 
   1    2    3    4    5    6    7    8 

$Mj
ll11 ll12 ll13 ll14 ll21 ll22 ll23 ll24 
  10   11   12   13   14   15   16   17 

$dn
 ll1  ll2 
"l1" "l2" 
like image 23
jdobres Avatar answered Jan 13 '23 10:01

jdobres