I have a data.frame set up like this:
Group 1 Group 2 count
a aa 1
b ab 6
c ac 7
I would like to reshape it to report the sum of the count by Group 1 over each of Group 2, like this:
Group 1 aa ab ac
a 1 0 0
b 0 6 0
c 0 0 7
I have looked into using aggregate, melt, and cast, but cannot figure a way to separate out the multiple groups into separate columns.
R: Pivoting using 'spread' function gets me to the point where I have a table with multiple rows for Group 1.
df %>%
group_by(`Group 1`) %>%
mutate(id2 = sequence(n())) %>%
spread(`Group 2`, "count")
Group 1 id2 aa ab ac
a 1 1 0 0
a 2 0 4 0
a 3 0 0 7
a 4 1 0 0
a 5 1 0 0
b 6 0 6 0
b 7 3 0 0
b 8 0 0 5
I still need to reduce this to sums for each Group 1
entry.
Like this:
Group 1 aa ab ac
a 2 4 7
b 3 6 5
I thought I could maybe add aggregate to the chain, but I can't get it to work on multiple columns