简体   繁体   中英

Summing values in a column and grouping by another column in R

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
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM