0

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...

2 Answers 2

3

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 NAs instead of 0 will do, then simply map_dfr(lst, ~ .x %>% pivot_wider(names_from = a, values_from = b)) will return the expected output.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to have been of help. :)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.