首页 > 解决方案 > 如何对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")))

标签: rgis

解决方案


尝试以下操作:

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]))

推荐阅读