Skip to contents

This function is typically useful when you want to pipe data into a summary and then join back the data to the summary. It joins by all shared columns using a "many-to-many" relationship.

Usage

join_to(x, y)

Arguments

x, y

A pair of data frames, data frame extensions (e.g. a tibble), or lazy data frames (e.g. from dbplyr or dtplyr). See Methods, below, for more details.

Value

A data frame with all columns in x and y and all rows in y, except the columns and resulting duplicates matched by the argument excluding.

See also

Examples

library(dplyr, warn.conflicts = FALSE)


product <- tibble(companies_id = 1:3, x = 11:13, y = letters[c(1, 1, 2)])
product
#> # A tibble: 3 × 3
#>   companies_id     x y    
#>          <int> <int> <chr>
#> 1            1    11 a    
#> 2            2    12 a    
#> 3            3    13 b    

# Easy to pipe
product |>
  summarize(mean = mean(x), .by = "y") |>
  join_to(product)
#> # A tibble: 3 × 4
#>   companies_id     x y      mean
#>          <int> <int> <chr> <dbl>
#> 1            1    11 a      11.5
#> 2            2    12 a      11.5
#> 3            3    13 b      13  



# Special method for 'tilt_profile'

company <- tibble(companies_id = 1:3)
company
#> # A tibble: 3 × 1
#>   companies_id
#>          <int>
#> 1            1
#> 2            2
#> 3            3

result <- tilt_profile(nest_levels(product, company))
result |> class()
#> [1] "tilt_profile" "tbl_df"       "tbl"          "data.frame"  
result
#> # A tibble: 3 × 3
#>   companies_id product          company         
#> *        <int> <list>           <list>          
#> 1            1 <tibble [1 × 2]> <tibble [1 × 0]>
#> 2            2 <tibble [1 × 2]> <tibble [1 × 0]>
#> 3            3 <tibble [1 × 2]> <tibble [1 × 0]>

# Easy to pipe.
joint <- result |>
  unnest_product() |>
  summarise(mean = mean(x), .by = "y") |>
  print() |>
  join_to(result)
#> # A tibble: 2 × 2
#>   y      mean
#>   <chr> <dbl>
#> 1 a      11.5
#> 2 b      13  
#> Warning: `x` and `y` have no shared columns. Returning `y`

# Note the summary has no shared columns with `company` so it joins nothing
joint |> unnest_company()
#> # A tibble: 3 × 1
#>   companies_id
#>          <int>
#> 1            1
#> 2            2
#> 3            3

# Same as when joining to `product` (see avove)
joint |> unnest_product()
#> # A tibble: 3 × 4
#>   companies_id     x y      mean
#>          <int> <int> <chr> <dbl>
#> 1            1    11 a      11.5
#> 2            2    12 a      11.5
#> 3            3    13 b      13