如何通过对R中的条目进行分组来创建时间序列?

时间:2013-03-07 15:34:39

标签: r count group-by time-series

我想创建一个从2004年1月1日到2010年12月31日的R中每日死亡率数据的时间序列。我现在拥有的原始数据(.csv文件),列为日 - 月 - 年每一行都是死亡案件。因此,如果某一天的死亡率例如等于4,则该日期有四行。如果在特定日期没有报告死亡病例,则在数据集中省略该日。

我需要的是一个2557行的时间序列(从2004年1月1日至2010年12月31日),其中列出了每天死亡病例的总数。如果某一天没有死亡案例,我仍然需要那天在列表中分配“0”。

有谁知道怎么做?

谢谢, Gosia

原始数据示例:

day month   year
1   1   2004
3   1   2004
3   1   2004
3   1   2004
6   1   2004
7   1   2004

我需要什么:

day month   year    deaths
1   1   2004    1
2   1   2004    0
3   1   2004    3
4   1   2004    0
5   1   2004    0
6   1   2004    1

1 个答案:

答案 0 :(得分:3)

df <- read.table(text="day month   year
1   1   2004
3   1   2004
3   1   2004
3   1   2004
6   1   2004
7   1   2004",header=TRUE)

#transform to dates
dates <- as.Date(with(df,paste(year,month,day,sep="-")))

#contingency table
tab <- as.data.frame(table(dates))
names(tab)[2] <- "deaths"
tab$dates <- as.Date(tab$dates)

#sequence of dates
res <- data.frame(dates=seq(from=min(dates),to=max(dates),by="1 day"))
#merge
res <- merge(res,tab,by="dates",all.x=TRUE)
res[is.na(res$deaths),"deaths"] <- 0
res
#       dates deaths
#1 2004-01-01      1
#2 2004-01-02      0
#3 2004-01-03      3
#4 2004-01-04      0
#5 2004-01-05      0
#6 2004-01-06      1
#7 2004-01-07      1