Similar assumption as GuedesBF, but:
- using
id
as a join var;
- joining individually on each of
Criteria #
; then
- summing all possible
Amount
s.
I don't get the right results, but there's no combination I found that produces your expected output ... so perhaps:
library(dplyr)
df1 %>%
left_join(df2, by = c("id", "Criteria 1" = "Date")) %>%
left_join(df2, by = c("id", "Criteria 2" = "Color")) %>%
group_by(id, `Criteria 1`, `Criteria 2`) %>%
summarize(Amount = sum(c(Amount.x, Amount.y), na.rm = TRUE)) %>%
ungroup()
# # A tibble: 3 × 4
# id `Criteria 1` `Criteria 2` Amount
# <int> <chr> <chr> <int>
# 1 1 3/1/2022 Black 30
# 2 2 5/2/2022 Black 10
# 3 3 3/1/2022 Blue 50
If you need to join on both simultaneously, then this only differs from GuedesBF's answer by the inclusion of id
:
df1 %>%
left_join(df2, by = c("id", "Criteria 1" = "Date", "Criteria 2" = "Color")) %>%
group_by(id, `Criteria 1`, `Criteria 2`) %>%
summarize(Amount = sum(Amount, na.rm = TRUE)) %>%
ungroup()
# # A tibble: 3 × 4
# id `Criteria 1` `Criteria 2` Amount
# <int> <chr> <chr> <int>
# 1 1 3/1/2022 Black 15
# 2 2 5/2/2022 Black 0
# 3 3 3/1/2022 Blue 25
Data
df1 <- structure(list(id = 1:3, "Criteria 1" = c("3/1/2022", "5/2/2022", "3/1/2022"), "Criteria 2" = c("Black", "Black", "Blue")), class = "data.frame", row.names = c(NA, -3L))
df2 <- structure(list(id = 1:6, Date = c("3/1/2022", "5/2/2022", "3/1/2022", "5/2/2022", "4/1/2022", "3/1/2022"), Color = c("Black", "Red", "Blue", "Red", "Black", "Black"), Amount = c(15L, 10L, 25L, 10L, 15L, 45L)), class = "data.frame", row.names = c(NA, -6L))
df3 <- structure(list(id = 1:3, "Criteria 1" = c("3/1/2022", "5/2/2022", "3/1/2022"), "Criteria 2" = c("Black", "Black", "Blue"), Amount = c(60L, 0L, 25L)), class = "data.frame", row.names = c(NA, -3L))