library(tidyverse)
find_sums <- function(vec, target) {
# return data frame of matches for each elements of vec that sum to target
match_df <- expand_grid(
tibble(row1 = 1:length(vec), value1 = vec),
tibble(row2 = 1:length(vec), value2 = vec)
) %>%
filter(value1 + value2 == target,
row1 <= row2) %>%
mutate(match_id = 1:n())
return(match_df)
}
reference_matches <- function(df, col_name, target) {
# find the matches of sums in df column that sum to target and return rows of the df
match_df <- find_sums(pull(df, col_name), target)
match_df_long <- match_df %>% pivot_longer(contains("row"), values_to = "row_num")
left_join(match_df_long %>% select(match_id, row_num),
df %>% mutate(row_num = 1:n()),
by = "row_num")
}
reference_matches(iris, "Sepal.Length", 10)
#> # A tibble: 376 x 7
#> match_id row_num Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <int> <int> <dbl> <dbl> <dbl> <dbl> <fct>
#> 1 1 1 5.1 3.5 1.4 0.2 setosa
#> 2 1 2 4.9 3 1.4 0.2 setosa
#> 3 2 1 5.1 3.5 1.4 0.2 setosa
#> 4 2 10 4.9 3.1 1.5 0.1 setosa
#> 5 3 1 5.1 3.5 1.4 0.2 setosa
#> 6 3 35 4.9 3.1 1.5 0.2 setosa
#> 7 4 1 5.1 3.5 1.4 0.2 setosa
#> 8 4 38 4.9 3.6 1.4 0.1 setosa
#> 9 5 1 5.1 3.5 1.4 0.2 setosa
#> 10 5 58 4.9 2.4 3.3 1 versicolor
#> # ... with 366 more rows
reference_matches(iris, "Sepal.Length", 9.8)
#> # A tibble: 262 x 7
#> match_id row_num Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <int> <int> <dbl> <dbl> <dbl> <dbl> <fct>
#> 1 1 1 5.1 3.5 1.4 0.2 setosa
#> 2 1 3 4.7 3.2 1.3 0.2 setosa
#> 3 2 1 5.1 3.5 1.4 0.2 setosa
#> 4 2 30 4.7 3.2 1.6 0.2 setosa
#> 5 3 2 4.9 3 1.4 0.2 setosa
#> 6 3 2 4.9 3 1.4 0.2 setosa
#> 7 4 2 4.9 3 1.4 0.2 setosa
#> 8 4 10 4.9 3.1 1.5 0.1 setosa
#> 9 5 2 4.9 3 1.4 0.2 setosa
#> 10 5 35 4.9 3.1 1.5 0.2 setosa
#> # ... with 252 more rows
Created on 2021-07-27 by the reprex package (v1.0.0)