I have the following two data frames:
df1 <- data.frame(group = rep("A", 5),
name = c("Brandon",
"Kyler",
"Trent",
"Lesa",
"Michael"),
gender = c("M", "F", "M", "F", "M"),
days = c(50, 45, 32, 60, 48))
df2 <- data.frame(group = rep("B", 10),
name = c("Erica",
"Jared",
"Sara",
"Helen",
"Tom",
"Ron",
"Cy",
"Lynn",
"Ken",
"Judy"),
gender = c("F", "M", "F", "F", "M", "M", "M", "F", "M", "F"),
days = c(47, 49, 62, 80, 74, 30, 55, 58, 63, 25))
I want to filter df2 to include only the closest match to each row in the df1 data frame based on gender and days, with gender taking priority.
For example, in df1, "Brandon" has gender == M and days == 50. When we look at only gender == M in df2, we see that "Jared" is the closest to "Brandon" in days, so "Jared" would be selected for the "Brandon" match. In total, the resulting data frame would look like this:
# group name gender days
# B Jared M 49
# B Erica F 47
# B Ron M 30
# B Lynn F 58
# B Cy M 55
Additional rules:
This is a hierarchical merge, where
gendermatch takes priority overdayscloseness.Note that there are two equal distanced options to match to "Lesa" in
df1("Sara" and "Lynn"). Randomly select one of the two to match to "Lesa". In the final data frame above, the example chose "Lynn"."Jared" in
df2is equal distance from both "Brandon" and "Michael" indf1. Because "Jared" is already matched to "Brandon", he cannot also be matched to "Michael". Therfore, the match to "Michael" moves on to "Cy", which is the next best remaining match in terms ofgenderanddays.