gpt4 book ai didi

r - 如何对宽 R 数据框中的列和行求和?

转载 作者:行者123 更新时间:2023-12-02 18:22:40 24 4
gpt4 key购买 nike

我想通过对列和行求和来按数据框进行变异。

mydata <-structure(list(description.y = c("X1", "X2"), `2011` = c(13185.66, 
82444.01), `2012` = c(14987.61, 103399.4), `2013` = c(26288.98,
86098.22), `2014` = c(15238.21, 88540.04), `2015` = c(15987.11,
113145.1), `2016` = c(16324.57, 113196.2), `2017` = c(16594.87,
122167.57), `2018` = c(20236.02, 120058.21), `2019` = c(20626.69,
130699.68), `2020` = c(19553.83, 136464.31), `2021` = c(10426.32,
56392.28)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), groups = structure(list(description.y = c("X1",
"X2"), .rows = structure(list(1L, 2L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))

我可以像这样对行求和

mydata1 <- mydata %>% 
mutate(Total = rowSums(across(where(is.numeric))))

它提供了一个额外的列,其中包含行的总计 enter image description here

但我不确定如何在保留所有现有值的同时将列添加到数据框

我已经试过了,但它不起作用。有什么想法吗?

 mydata1 <- mydata %>% 
mutate(Total = rowSums(across(where(is.numeric)))) %>%
mutate(Total = colSums(across(where(is.numeric))))

最佳答案

更新:查看评论@Mwavu -> 非常感谢!使用 adorn_total() 的直接解决方案:

mydata %>% adorn_totals(where = c("row", "col"))

第一个回答:我们可以使用 adorn_totals()

library(dplyr)
library(janitor)
mydata %>%
mutate(Total = rowSums(across(where(is.numeric)))) %>%
adorn_totals()
 description.y     2011      2012      2013      2014      2015      2016      2017      2018      2019      2020     2021     Total
X1 13185.66 14987.61 26288.98 15238.21 15987.11 16324.57 16594.87 20236.02 20626.69 19553.83 10426.32 189449.9
X2 82444.01 103399.40 86098.22 88540.04 113145.10 113196.20 122167.57 120058.21 130699.68 136464.31 56392.28 1152605.0
Total 95629.67 118387.01 112387.20 103778.25 129132.21 129520.77 138762.44 140294.23 151326.37 156018.14 66818.60 1342054.9

关于r - 如何对宽 R 数据框中的列和行求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70661891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com