r - 我将如何为特定列中的每个值添加一个总计行,该行基于其他列进行计算,

标签 r

假设我有这个数据框

enter image description here

我要的是这个

enter image description here

我想做的是创建对月份变量进行分组的行,然后获取总变量的总和,以及该月所有个人值的 days_month 变量的唯一值。

我只是想知道是否有一种简单的方法可以做到这一点,它不涉及多次传播和收集装饰总数,我必须在总计相加后将一个月中的天数改回原始值等。是否有有快速简便的方法吗?

最佳答案

一个选项是按“month”、“days_in_month”分组并通过 group_mapping

应用 adorn_total
library(dplyr)
library(janitor)
df1 %>% 
    group_by(month, days_in_month) %>%
    group_map(~ .x %>%
                  adorn_totals("row"))  %>%
    select(names(df1))
# A tibble: 10 x 4
# Groups:   month, days_in_month [2]
#   month person total days_in_month
#   <int> <chr>  <int>         <int>
# 1     1 John       7            31
# 2     1 Jane      18            31
# 3     1 Tim       20            31
# 4     1 Cindy     11            31
# 5     1 Total     56            31
# 6     2 John      18            28
# 7     2 Jane      13            28
# 8     2 Tim       15            28
# 9     2 Cindy      9            28
#10     2 Total     55            28

如果我们需要其他统计数据,我们可以在 group_map 中获取它

library(tibble)
df1 %>% 
  group_by(month, days_in_month) %>% 
  group_map(~ bind_rows(.x, tibble(person = "Mean", total = mean(.x$total))))

数据

df1 <- structure(list(month = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), person = c("John", 
   "Jane", "Tim", "Cindy", "John", "Jane", "Tim", "Cindy"), total = c(7L, 
 18L, 20L, 11L, 18L, 13L, 15L, 9L), days_in_month = c(31L, 31L, 
  31L, 31L, 28L, 28L, 28L, 28L)), class = "data.frame", row.names = c(NA, 
-8L))

关于r - 我将如何为特定列中的每个值添加一个总计行,该行基于其他列进行计算,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54831166/

相关文章:

r - 如何用R创建时间散点图?

r - 通过R中的for循环将多个图表保存在1个pdf页面中

R 包 'partykit' ctree_control 中未使用的参数

r - 获取循环内对象的名称

r - 在多列中拆分列并保留下一个

r - 根据R中的另一个矩阵/df替换df/matrix中的值

R找到两条线之间的角度,当有斜率和截距系数时

r - 将R中的多个二进制列合并为一列并保留位置

r - 在R中绘制数据集的概率密度/质量函数

r - 在 R 中创建一个新列来查看前两列中的数据并分配因子水平?