This problem resembles anscombe data reshaping, well resolved by data table first , followed by dplyr.
> library(data.table)
> library(magrittr)
> melt(setDT(df),
+ measure.vars = patterns(c("Name", "Group")),
+ value.name=c('Name', 'Value'),
+ variable.name = 'Group', na.rm = T) %>%
+ dcast(Name ~ Group, value.var="Value", fill=0)
Name 1 2 3
1: A 2 1 4
2: B 4 2 7
3: C 7 4 0
4: D 6 7 4
5: E 4 0 0
6: F 0 6 0
7: H 0 4 0
8: I 0 0 6
9: M 0 0 9
Interesting problem. I'm trying to use dplyr to solve this but it's turning to be pretty challenging.
Wouldn't full join do the trick here? (iteratively)
Yes, but you'd need to split the df into tables with 2 cols each and do an iterative full join with a manual stop. Plus, it is not a generalized solution that would work across any number of 2n cols so I'm curious if any sort of pivot can do it.