How to merge the two different data frame column with row matching?

I just want to merge the two different data frame column with row matching

eg: df1

        name  age

 66     A       Na
123     B       Na
125     C       20
127     D       Na

df2:

         a

 66     24
123     32
127     42
        name age

 66     A       24
123     B       32
125     C       20
127     D       42

66,123,125,127 are row numbers.

I can't quite tell from your question whether or not these are two data frames for which you want to bind the rows together, or if you want to join them together using the row number as an id of sorts.

If you can turn this into a self-contained reprex (short for reproducible example)? It will help us help you. For pointers specific to the community site, check out the reprex FAQ.

For the former (all rows from both data frames), you can use rbind() or dplyr::bind_rows() (I'm sure there are other options, too), however, this isn't a good idea, given your data frames do not have the same columns.

For the latter, you'll want to turn the row numbers into proper variables so you can use a join.

Below, I'm using a full join, which will match by the variable I've called "row". This will result in two columns, age.x and age.y, for which I choose the first non-missing value with dplyr::coalesce(). I then get rid of the age.x and age.y variables by selecting only columns/variables with names that do not contain the "." character.

library(tidyverse)
df1 <- tibble::tribble(
  ~row, ~name, ~age,
    66,   "A", NA,
   123,   "B", NA,
   125,   "C", 20,
   127,   "D", NA
  )

df2 <- tibble::tribble(
  ~row, ~age,
    66,   24,
   123,   32,
   127,   42
  )

combo <- full_join(df1, df2, by = "row") %>%
            mutate(age = coalesce(age.x, age.y)) %>%
            select(-contains("."))

combo
#> # A tibble: 4 x 3
#>     row name    age
#>   <dbl> <chr> <dbl>
#> 1    66 A        24
#> 2   123 B        32
#> 3   125 C        20
#> 4   127 D        42

Created on 2018-10-02 by the reprex package (v0.2.1.9000)

2 Likes