3

2004年1月1日から2010年12月31日までのRの日次死亡率データの時系列を作成したいと思います。現在持っている生データ(.csvファイル)には、日-月-年とすべての行が列としてあります。死の場合です。したがって、特定の日の死亡率がたとえば4に等しい場合、その日付の行は4つあります。特定の日に死亡例が報告されていない場合、その日はデータセットで省略されます。

必要なのは、2557行(2004年1月1日から2010年12月31日まで)の時系列で、1日あたりの死亡症例の総数がリストされています。特定の日に死亡例がない場合でも、その日は「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
4

1 に答える 1

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
于 2013-03-07T16:25:02.747 に答える