簡體   English   中英

試圖在 r 中計算每月、每年的死亡人數

[英]Trying to sum deaths per month, year in r

我是 r 的初學者。

我有以下格式的“日期”向量:

head(z$dod)
[1] "2017-08-15" "2017-08-21" "2017-08-20" "2017-08-22" "2017-08-31"
[6] "2017-09-04"

我有一個二進制變量; 在這些日期中,麻疹死亡為 1,非麻疹死亡為 0。

我想將每月、每年的麻疹死亡頻率(即刪除我的日期中的天數)和 plot 相加。 我嘗試了各種方法,例如按“月”將其分成休息時間或如下:

z$dod<-as.POSIXlt(z$dod, format="%d-%m-%Y")
mon<-z$dod$mon
yr<-z$dod$year
mon_yr<-as.factor(paste(mon, yr, sep="/"))
z$dod<-mon_yr

c <- ggplot(z, aes(factor(dod)))
c + geom_bar()

或嘗試匯總:

measledeath.mon_yr <- aggregate(z$measledeath, by=list(z$mon_yr), sum) 
colnames(measledeath.mon_yr) <- c('date', 'deaths')

但到目前為止,沒有人提供我正在尋找的東西。 go 關於這個的最佳方法是什么?

這是dplyrlubridate的解決方案:

library(dplyr)
library(lubridate)
df %>% 
  mutate(year = year(date),
         month = month(date),
         year_mon = paste(year, month, sep = "-")) %>% 
  group_by(year_mon) %>% 
  summarise(sum = sum(measles)))

# A tibble: 3 x 2
  year_mon   sum
  <chr>    <dbl>
1 2017-10     12
2 2017-8       5
3 2017-9      20

數據

df <- structure(list(date = structure(c(17399, 17400, 17401, 17402, 
17403, 17404, 17405, 17406, 17407, 17408, 17409, 17410, 17411, 
17412, 17413, 17414, 17415, 17416, 17417, 17418, 17419, 17420, 
17421, 17422, 17423, 17424, 17425, 17426, 17427, 17428, 17429, 
17430, 17431, 17432, 17433, 17434, 17435, 17436, 17437, 17438, 
17439, 17440, 17441, 17442, 17443, 17444, 17445, 17446, 17447, 
17448, 17449, 17450, 17451, 17452, 17453, 17454, 17455, 17456, 
17457, 17458, 17459, 17460), class = "Date"), measles = c(0, 
0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 
1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 
0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1)), row.names = c(NA, 
-62L), class = c("tbl_df", "tbl", "data.frame"))

在 Base-R 中,我們可以像這樣一起使用sapplysplitformat

> z
       dates measledeath
1 2017-08-15           1
2 2017-08-21           2
3 2017-08-20           3
4 2017-08-22           4
5 2017-09-30           5



sapply(split(z$measledeath,format(z$dates, format = "%Y-%m")), sum)

2017-08 2017-09 
     10       5 

編輯,日期必須是as.Date格式。


數據:

z <- data.frame(    
        dates=as.Date(c("2017-08-15", "2017-08-21", "2017-08-20", "2017-08-22", "2017-09-30")),
        measledeath = c(1,2,3,4,5))

暫無
暫無

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

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