0

I have a list of data frames. I want to merge them vertically on column name.

Here are three data frames in my list, for example:

Precinct VoterTurnout Johnson Jameson
4030     45           20      25

And this one...

Precinct VoterTurnout Jimson
1234     33           20

And the third...

Precinct VoterTurnout Jhohnshohn
4321     555          222

These dataframes are in a list named listDFs. How do I merge them to look like this?

Precinct VoterTurnout Johnson Jameson Jimson Jhohnshohn
4030     45           20      25      NA     NA
1234     33           NA      NA      20     NA
4321     555          NA      NA      NA     222
Username
  • 3,463
  • 11
  • 68
  • 111

1 Answers1

0

Using the tidyverse packages, you can use Reduce and full_join() to accomplish it:

First, let's create the "sub-tables" as tibbles:

library(tidyverse)

a <- tribble(
  ~Precinct, ~VoterTurnout, ~Johnson,
  4030,     45,           20
)

b <- tribble(
  ~Precinct, ~VoterTurnout, ~Jimson,
  1234,     33,           20
)

c <- tribble(
  ~Precinct, ~VoterTurnout,  ~Jhohnshohn,
  4321,     555,          222
)

Now that we have tables a , b, and c we can join the list recursively with Reduce:

ll <- list(a,b,c)

ll %>% 
  reduce(full_join)

Note that the NA's appear where they should when you use a full_join.

Let's inspect the result:

    # A tibble: 3 × 5
  Precinct VoterTurnout Johnson Jimson Jhohnshohn
     <dbl>        <dbl>   <dbl>  <dbl>      <dbl>
1     4030           45      20     NA         NA
2     1234           33      NA     20         NA
3     4321          555      NA     NA        222
Dan
  • 1,711
  • 2
  • 24
  • 39