I have a dataset with ids and associated values:
df <- data.frame(id = c("1", "2", "3"), value = c("12", "20", "16"))
I have a lookup table that matches the id to another reference label ref:
lookup <- data.frame(id = c("1", "1", "1", "2", "2", "3", "3", "3", "3"), ref = c("a", "b", "c", "a", "d", "d", "e", "f", "a"))
Note that id to ref is a many-to-many match: the same id can be associated with multiple ref, and the same ref can be associated with multiple id.
I'm trying to split the value associated with the df$id column equally into the associated ref columns. The output dataset would look like:
output <- data.frame(ref = "a", "b", "c", "d", "e", f", value = "18", "4", "4", "14", "4", "4")
| ref | value |
|---|---|
| a | 18 |
| b | 4 |
| c | 4 |
| d | 14 |
| e | 4 |
| f | 4 |
I tried splitting this into four steps:
- calling pivot_wider on
lookup, turning rows with the sameidvalue into columns (e.g.,a,b,c.) - merging the two datasets based on
id - dividing each
df$valueequally intoa,b,c, etc. columns that are not empty - transposing the dataset and summing across the
idcolumns.
I can't figure out how to make step (3) work, though, and I suspect there's a much easier approach.