dplyr merge two data frames code example

Example: dplyr::lef_join

# "Mutating" joins combine variables from the LHS and RHS
band_members %>% inner_join(band_instruments)#> Joining, by = "name"#> # A tibble: 2 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 John  Beatles guitar
#> 2 Paul  Beatles bass  band_members %>% left_join(band_instruments)#> Joining, by = "name"#> # A tibble: 3 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 Mick  Stones  <NA>  
#> 2 John  Beatles guitar
#> 3 Paul  Beatles bass  band_members %>% right_join(band_instruments)#> Joining, by = "name"#> # A tibble: 3 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 John  Beatles guitar
#> 2 Paul  Beatles bass  
#> 3 Keith <NA>    guitarband_members %>% full_join(band_instruments)#> Joining, by = "name"#> # A tibble: 4 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 Mick  Stones  <NA>  
#> 2 John  Beatles guitar
#> 3 Paul  Beatles bass  
#> 4 Keith <NA>    guitar
# "Filtering" joins keep cases from the LHS
band_members %>% semi_join(band_instruments)#> Joining, by = "name"#> # A tibble: 2 x 2
#>   name  band   
#>   <chr> <chr>  
#> 1 John  Beatles
#> 2 Paul  Beatlesband_members %>% anti_join(band_instruments)#> Joining, by = "name"#> # A tibble: 1 x 2
#>   name  band  
#>   <chr> <chr> 
#> 1 Mick  Stones
# "Nesting" joins keep cases from the LHS and nests the RHS
band_members %>% nest_join(band_instruments)#> Joining, by = "name"#> # A tibble: 3 x 3
#>   name  band    band_instruments
#> * <chr> <chr>   <list>          
#> 1 Mick  Stones  <tibble [0 × 1]>
#> 2 John  Beatles <tibble [1 × 1]>
#> 3 Paul  Beatles <tibble [1 × 1]>
# To suppress the message, supply by
band_members %>% inner_join(band_instruments, by = "name")#> # A tibble: 2 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 John  Beatles guitar
#> 2 Paul  Beatles bass  # This is good practice in production code

# Use a named `by` if the join variables have different names
band_members %>% full_join(band_instruments2, by = c("name" = "artist"))#> # A tibble: 4 x 3
#>   name  band    plays 
#>   <chr> <chr>   <chr> 
#> 1 Mick  Stones  <NA>  
#> 2 John  Beatles guitar
#> 3 Paul  Beatles bass  
#> 4 Keith <NA>    guitar# Note that only the key from the LHS is kept

Tags:

R Example