2013-03-07 22 views
3

我想創建01/01/2004時間序列,直到R.我有現在(.csv文件)的原始數據,具有與列日每日死亡率數據31/12/2010 - 月 - 年每一行都是死亡案例。因此,如果某一天的死亡率例如等於四,那麼該日期有四行。如果在特定日期沒有報告死亡病例,則在數據集中省略該日。如何通過R中的條目進行分組創建時間序列?

我需要的是一個時間序列與2557行(從01/01/2004至31/12/2010),其中每天死亡病例總數列。如果某一天,無死亡病例,我還需要這一天是在列表中分配給它一個「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 
+0

您應該添加的樣本數據。 – 2013-03-07 15:52:01

回答

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 
+0

@羅蘭德 - 非常感謝!正是我需要的,Gosia – Gosia 2013-03-08 09:08:08

+0

@Gosia隨意勾選上這個答案的上方左側的選中標記。這讓人們知道,你的問題已得到滿意答覆。 – Roland 2013-03-08 10:29:50

相關問題