tidyr join 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
#>
#> 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
#>
#> 1 Mick Stones
#> 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
#>
#> 1 John Beatles guitar
#> 2 Paul Beatles bass
#> 3 Keith guitarband_members %>% full_join(band_instruments)#> Joining, by = "name"#> # A tibble: 4 x 3
#> name band plays
#>
#> 1 Mick Stones
#> 2 John Beatles guitar
#> 3 Paul Beatles bass
#> 4 Keith guitar
# "Filtering" joins keep cases from the LHS
band_members %>% semi_join(band_instruments)#> Joining, by = "name"#> # A tibble: 2 x 2
#> name band
#>
#> 1 John Beatles
#> 2 Paul Beatlesband_members %>% anti_join(band_instruments)#> Joining, by = "name"#> # A tibble: 1 x 2
#> name band
#>
#> 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
#> *
#> 1 Mick Stones
#> 2 John Beatles
#> 3 Paul Beatles
# To suppress the message, supply by
band_members %>% inner_join(band_instruments, by = "name")#> # A tibble: 2 x 3
#> name band plays
#>
#> 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
#>
#> 1 Mick Stones
#> 2 John Beatles guitar
#> 3 Paul Beatles bass
#> 4 Keith guitar# Note that only the key from the LHS is kept