简体   繁体   中英

how to merge R list into a data.frame by rows

I have a list of data.frames. It looks somehow like this:

> lst <- list(data.frame(a=c(1,2),b=c(33,44)),data.frame(a=c(2,3),b=c(55,66)))
> lst
[[1]]
  a  b
1 1 33
2 2 44

[[2]]
  a  b
1 2 55
2 3 66

Obviously, mine is longer (more than 20 items in list).

What I want to get is something like:

     1   2   3
b.1  33  44  0
b.2  0   55  66

I tried with Reduce and merge, but wasn't really successfull so far...

do this

lst <- list(data.frame(a=c(1,2),b=c(33,44)),data.frame(a=c(2,3),b=c(55,66)))

library(tidyverse)

map_dfr(lst, ~ .x %>% pivot_wider(names_from = a, values_from = b)) %>%
  mutate(across(everything(), ~ifelse(is.na(.), 0, .)))
#> # A tibble: 2 x 3
#>     `1`   `2`   `3`
#>   <dbl> <dbl> <dbl>
#> 1    33    44     0
#> 2     0    55    66

Created on 2021-05-10 by the reprex package (v2.0.0)

If NA s instead of 0 will do, then simply map_dfr(lst, ~.x %>% pivot_wider(names_from = a, values_from = b)) will return the expected output.

Here is a way with reduce . If you want the column / row names as you specified, you can then add them in.

library(dplyr)
library(purrr)

reduce(lst, full_join, by = "a") %>% 
  select(-a) %>% 
  transpose() %>% 
  set_names(seq(.)) %>% 
  map_dfc(unlist)

# # A tibble: 3 x 3
#     `1`   `2`   `3`
#   <dbl> <dbl> <dbl>
# 1    33    44    NA
# 2    NA    55    66

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM