is there other method to tag “many-to-many、one-to-many and many-to-one” three relationship, like the example below.
df1 <- data.frame(
id1 = c(1, 1, 3, 4),
value1 = c("A", "B", "C", "D")
)
df2 <- data.frame(
id2 = c(1, 1, 3, 3, 4),
value2 = c("X", "Y", "Z1", "Z2", "W")
)
# Performing a left join to tag the many-to-many relationship and adding a tag variable
result <- df1 %>%
left_join(df2, by = c("id1" = "id2")) %>%
group_by(id1) %>%
mutate(
tag = if_else(n() > 1, "many-to-many", "one-to-many")
) %>%
ungroup()
result
# A tibble: 7 × 5
id1 value1 id2 value2 tag
<dbl> <chr> <dbl> <chr> <chr>
1 1 A 1 X many-to-many
2 1 A 1 Y many-to-many
3 1 B 1 X many-to-many
4 1 B 1 Y many-to-many
5 3 C 3 Z1 many-to-many
6 3 C 3 Z2 many-to-many
7 4 D 4 W one-to-many
like the example above, I have taged the “many-to-many、one-to-many” but no many-to-one
New contributor
qizheng li is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.