我想知道如何找到一個月和一年的列的總和(在本例中是 AgeGroup_20_to_24 列)。這是示例資料:
https://i.stack.imgur.com/E23Th.png
我基本上想找到每月/每年的病例總數。例如: 01/2020 = 該年齡組的總病例數 02/2020 = 該年齡組的總病例數
我試過這樣做,但是我得到了這個:
https://i.stack.imgur.com/1eH0O.png
xAge20To24 <- covid%>%
mutate(dates=mdy(Date), year = year(dates), month = month(dates))%>%
mutate(total = sum(AgeGroup_20_to_24))%>%
select(Date, year, month, AgeGroup_20_to_24)%>%
group_by(year)
View(xAge20To24)
任何幫助將不勝感激。
結構(串列(日期 = c(“2020 年 3 月 9 日”、“2020 年 3 月 10 日”、“2020 年 3 月 11 日”、“2020 年 3 月 12 日”、“2020 年 3 月 13 日”、“3 /14/2020"), AgeGroup_0_to_19 = c(1, 0, 2, 0, 0, 2), AgeGroup_20_to_24 = c(1, 0, 2, 0, 2, 1), AgeGroup_25_to_29 = c(1, 0, 1 , 2, 2, 2), AgeGroup_30_to_34 = c(0, 0, 2, 3, 4, 3), AgeGroup_35_to_39 = c(3, 1, 2, 1, 2, 1), AgeGroup_40_to_44 = c(1, 2, 1, 3, 3, 1), AgeGroup_45_to_49 = c(1, 0, 0, 2, 0, 1), AgeGroup_50_to_54 = c(2, 1, 1, 1, 0, 1), AgeGroup_55_to_59 = c(1, 0 , 1, 1, 1, 2), AgeGroup_60_to_64 = c(0, 2, 2, 1, 1, 3), AgeGroup_70_plus = c(2, 0, 2, 0, 0, 0)), row.names = c (NA, -6L), 類 = c("tbl_df", "tbl", "data.frame"))
uj5u.com熱心網友回復:
我不確定你的問題和你的資料是否匹配。您要求按月匯總資料,但您的資料僅包括 3 月份的條目。我在下面提供了兩個匯總資料的示例,一個使用整個日期,另一個使用按日匯總,因為我們不能使用月份。如果您的完整資料集包含更多月份,您可以將日期換成月份。首先,可以使用以下代碼快速總結日期:
#### Load Library ####
library(tidyverse)
library(lubridate)
#### Pivot and Summarise Data ####
covid %>%
pivot_longer(cols = c(everything(),
-Date),
names_to = "AgeGroup",
values_to = "Cases") %>%
group_by(Date) %>%
summarise(Sum_Cases = sum(Cases))
這會將您的資料轉換為長格式,按整個日期分組,然后匯總案例,從而為您提供按日期計算的資料總和:
# A tibble: 6 × 2
Date Sum_Cases
<chr> <dbl>
1 3/10/2020 6
2 3/11/2020 16
3 3/12/2020 14
4 3/13/2020 15
5 3/14/2020 17
6 3/9/2020 13
使用相同的pivot_longer原則,您可以像以前一樣將資料更改為日期格式,轉為更長的格式,然后按天分組,然后總結案例:
#### Theoretical Example ####
covid %>%
mutate(Date=mdy(Date),
Year = year(Date),
Month = month(Date),
Day = day(Date)) %>%
pivot_longer(cols = c(everything(),
-Date,-Year,-Month,-Day),
names_to = "AgeGroup",
values_to = "Cases") %>%
group_by(Day) %>% # use by day instead of month
summarise(Sum_Cases = sum(Cases))
您可以在下面看到。在這里我們可以看到第 14 位的病例最多:
# A tibble: 6 × 2
Day Sum_Cases
<int> <dbl>
1 9 13
2 10 6
3 11 16
4 12 14
5 13 15
6 14 17
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526983.html
標籤:r
