Reputation: 384
This is a very basic question I am having trouble with. See the sample data below. I am trying create a new df with rolled up information under each persons name of their sum totals from each department.
I've been working with the dplyr package using the mutate and groupby and aggregate functions by to no luck. Is there a simple way to achieve this? The result of this task will then be plotted on a correlation plot.
Here is a reproducible example:
df <- tibble::tribble(
~Dept, ~Mike, ~Steve, ~Tom,
"Dept1", 1, 1, 0,
"Dept1", 1, 1, 0,
"Dept1", 0, 0, 1,
"Dept2", 0, 1, 1,
"Dept2", 0, 0, 0,
"Dept2", 0, 1, 1,
"Dept2", 0, 1, 0
)
Expected output:
result <- tibble::tribble(
~Dept, ~Mike, ~Steve, ~Tom,
"Dept1", 2, 2, 1,
"Dept2", 1, 2, 2
)
Upvotes: 1
Views: 1175
Reputation: 2115
summarise_all
is your friend here.
summarise_all(group_by(df, Dept), sum)
# # A tibble: 2 x 4
# Dept Mike Steve Tom
# <chr> <dbl> <dbl> <dbl>
# 1 Dept1 2 2 1
# 2 Dept2 0 3 2
Upvotes: 4