Home > OS >  How to combine lists with same names in r?
How to combine lists with same names in r?

Time:01-05

Lets assume I have several lists:

lsst=list();lsst[1]=0.55
names(lsst)[1]="A"

lsst2=list();lsst2[1]=0
 names(lsst2)[1]="A"

How to have the output dataframe

             A
 T1         0.55
 T2          0

CodePudding user response:

Use rbind.data.frame.

do.call(rbind.data.frame, list(T1=lsst, T2=lsst2))
#    A   
# T1 0.55
# T2 0   

CodePudding user response:

We may get the values of the objects in a list and use bind_rows

library(dplyr)
library(tibble)
mget(ls(pattern = 'lsst')) %>%
   bind_rows>% 
   mutate(rn = c("bvax", "bvin")) %>%
   column_to_rownames("rn") %>%
   as.matrix
       A
bvax 0.55
bvin 0.00

Or using base R

out <- do.call(rbind, lapply(mget(ls(pattern = 'lsst')), \(x) t(unlist(x))))
row.names(out) <- c("bvax", "bvin")
out
        A
bvax 0.55
bvin 0.00

CodePudding user response:

Another possible solution, based on purrr::map_dfr:

library(tidyverse)

lsst=list();lsst[1]=0.55
names(lsst)[1]="A"

lsst2=list();lsst2[1]=0
names(lsst2)[1]="A"

map_dfr(list(lsst, lsst2), ~ data.frame(.x) %>% set_names(., names(.x))) %>%
  `row.names<-`(str_c("T",1:2))

#>       A
#> T1 0.55
#> T2 0.00
  •  Tags:  
  • Related