r - 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.
解决方案
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)
推荐阅读
- mysql - 具有外部主节点的复制阵列中 RDS 快照的意外行为
- java - Java Android studio Application - 如何在用相机拍摄照片后正确重命名照片?
- python - 从 setup.py 目录导入子包或模块
- c# - 我正在尝试使用 html 提交按钮运行 asp.net 方法,但该方法无法运行?
- python - 按下特定键时增加值,然后在表格中记录值
- python - 在 Python 中以另一个变量的值为条件创建一个变量
- java - Java方法不会执行多次
- javascript - 你能写两次'for'吗?
- java - 无法创建 tempDir。java.io.tmpdir 设置为 /tmp
- java - 向服务器 HPSM9.41 webtier 推荐的 Tomcat 的 Java 堆大小