r - 如何对r中的行和列求和?
问题描述
我如何总结下表?我还有更多以“cumul”开头的列。我想按行和列求和。在用总和数据绘制折线图之后。
我也需要绘制图表以从数据表中提取相关信息的帮助。
CVE_ENT NOMGEO Pop2016 cumul13 cumul14 cumul15 cumul16
## 1 09 Azcapotzalco 408441 19 46 87 156
## 2 09 Coyoacán 621952 25 44 107 213
## 3 09 Cuajimalpa de Morelos 199809 66 75 93 122
Sum Column and Group By Expected Results
CVE_ENT cumul13total cumul14total cumul15total cumul16total
09 129 165 287 491
15 465 764 123 365
Sum Row & Group By Expected Results
CVE_ENT Total
09 298
15 567
# Edited code:
#group by and column sum
result1 <- sf_MC %>%
group_by(CVE_ENT) %>%
summarise(across(starts_with('cumu'), sum, na.rm = TRUE,
.names = '{col}_total'))
dput(result1)
Extracted Result using dput(result1) :
structure(list(CVE_ENT = c("09", "15", "17"), cumul13_total = c(493,
## 252, 13), cumul14_total = c(918, 540, 31), cumul15_total = c(1727,
## 1059, 65), cumul16_total = c(3358, 2141, 126), cumul17_total = c(5920,
## 3844, 303), cumul18_total = c(8916, 5869, 551), cumul19_total = c(13080,
## 8414, 872), cumul20_total = c(18212, 11818, 1196),.....cumul13_total = NA_integer_, cumul14_total = NA_integer_, cumul15_total = NA_integer_,
## cumul16_total = NA_integer_, cumul17_total = NA_integer_, cumul18_total = NA_integer_,
## cumul19_total = NA_integer_, class = "factor", .Label = c("constant",
## "aggregate", "identity")))
解决方案
尝试以下操作:
library(dplyr)
#group by and column sum
result1 <- sf_MC %>%
group_by(CVE_ENT) %>%
summarise(across(starts_with('cumu'), sum, na.rm = TRUE,
.names = '{col}_total'))
#rowwise sum
result2 <- cbind(result1[1], total = rowSums(result1[-1]))
推荐阅读
- c++ - Boost Interprocess:托管共享内存错误
- maven - lein jar 包含 project.clj 和 pom.xml
- c# - 从父 .xaml 文件中引用 resourceDictionary
- java - 如何防止 do while 循环重置?
- python - 打包 xlwings 错误导入 UDF
- javascript - Webpack 中的动态导入:可以在子文件夹之间分配块吗?
- python - Python蛮力密码猜测器
- java - Spring CriteriaBuilder 按名称搜索枚举
- python - 从python中的列表中删除重复项
- view - 使用 CouchDB 中的视图按过滤器搜索