簡體   English   中英

如何為特定列中的每個值添加總計行,以根據其他列進行計算,

[英]How would I add a Total Row for each value in a specific column, that does calculations based upon other columns,

假設我有這個數據框

在此處輸入圖片說明

我想要的是這個

在此處輸入圖片說明

我想做的是創建按月變量分組的行,然后該行獲取總計變量的總和,以及該月所有值的人的days_month變量的唯一值。

我只是想知道是否有一種簡單的方法來完成此操作,而該方法不涉及多次利差和裝飾總數,因此我必須在將總數相加后將每月的天數更改回原始值,等等。簡單的方法嗎?

一種選擇是按'month','days_in_month' adorn_totalgroup_map ping應用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM