-1

Assuming the following list:

a <- data.frame(id = 1:3, x  = 1:3)
b <- data.frame(id = 3:1, y  = 4:6)
my_list <- list(a, b)

my_list
# [[1]]
#   id x
# 1  1 1
# 2  2 2
# 3  3 3

# [[2]]
#   id y
# 1  3 4
# 2  2 5
# 3  1 6

I now want to column bind the list elements into a data frame/tibble while matching the respective rows based on the id variable, i.e. the outcome should be:

# A tibble: 3 x 3
     id     x     y
  <int> <int> <int>
1     1     1     6
2     2     2     5
3     3     3     4

I know how I can do it with some pivoting, but I'm wondering if there's a smarter way of doing it and I hoped there was some binding function that simply allows for specifying an id column?

Current approach:

library(tidyverse)
my_list %>%
  bind_rows() %>%
  pivot_longer(cols = -id) %>%
  filter(!is.na(value)) %>%
  pivot_wider()
zx8754
  • 52,746
  • 12
  • 114
  • 209
deschen
  • 10,012
  • 3
  • 27
  • 50

1 Answers1

3
reduce(my_list, full_join, by='id')
  id x y
1  1 1 6
2  2 2 5
3  3 3 4

If its only 2 dataframes:

invoke(full_join, my_list, by='id')
  id x y
1  1 1 6
2  2 2 5
3  3 3 4

If you are using base R, any of the following should work:

Reduce(merge, my_list)
do.call(merge, my_list)
Onyambu
  • 67,392
  • 3
  • 24
  • 53