【问题标题】:How to create timeseries by grouping entries in R?如何通过对 R 中的条目进行分组来创建时间序列?
【发布时间】:2013-03-07 15:34:39
【问题描述】:

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

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

有人知道怎么做吗?

谢谢, 戈西亚

原始数据示例:

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

【问题讨论】:

  • 您应该添加示例数据。

标签: r count group-by time-series


【解决方案1】:
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

【讨论】:

  • @Roland - 非常感谢!正是我需要的,Gosia
  • @Gosia 随意勾选此答案左上角的复选标记。这让人们知道,您的问题已得到您满意的回答。
猜你喜欢
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多