首页 > 解决方案 > R add totals to columns?

问题描述

I have a dataframe like this:

a b
1 4
2 5
3 6

I want to add a column totals like this:

      a b
      1 4
      2 5
      3 6
Total 6 15

I am trying to play with dplyr::summarise but without luck. Please advise.

标签: rdplyr

解决方案


Using the builtin data frame BOD try this:

addmargins(as.matrix(BOD), 1)

giving:

    Time demand
       1    8.3
       2   10.3
       3   19.0
       4   16.0
       5   15.6
       7   19.8
Sum   22   89.0

It could also be written like this (or use library(magrittr) in place of library(dplyr) since there is nothing from dplyr used here except what is imported from magrittr).

library(dplyr)

BOD %>%
    as.matrix %>%
    addmargins(1)

推荐阅读