2012-11-29 53 views
0

我有一個包含一個日期欄(這是一流的日期確實)和若干柱(類數字)更有效的方式在R中進行多個日期計算?

 first  last  date number 
1 Reynalda  Morley 1953-07-03  9 
2  Annice  Meador 1954-10-29  38 
3  Jude Pertuit 1956-08-23  49 
4 Viviana  Dance 1979-11-07  32 
5 Lavonda  Babst 1982-02-06  17 
6 Rachele Eisenhower 1985-11-12  27 
7  Ericka  Roesch 1987-05-02  22 
8 Giovanni  Bemis 1988-06-23  33 
9  Ferne  Mone 2005-12-21  36 
10 Anjanette Eppinger 2010-01-03  4 

我想通過每年行走並獲得累計到日期和框架一年的平均值。大概我想結果幀像落得:

year total.to.date average.this.year 
1 2001 128  32 
2 2002 128  0 
3 2003 145  17 
4 2004 227  27.3333333333333 
5 2005 267  20 

我知道我可以使用全系列的子集的每一個計算,但我也知道,如果我是聰明左右...也許tapply? ......我可以把它攪動一下。我是否需要添加庫來處理像這樣的日期?

回答

1

它與by函數一起使用。

dat <- read.table(text="first  last  date number 
1 Reynalda  Morley 1953-07-03  9 
2  Annice  Meador 1954-10-29  38 
3  Jude Pertuit 1956-08-23  49 
4 Viviana  Dance 1979-11-07  32 
5 Lavonda  Babst 1982-02-06  17 
6 Rachele Eisenhower 1985-11-12  27 
7  Ericka  Roesch 1987-05-02  22 
8 Giovanni  Bemis 1988-06-23  33 
9  Ferne  Mone 2005-12-21  36 
10 Anjanette Eppinger 2010-01-03  4", header = TRUE) 

dat$date <- as.Date(dat$date) 

這些命令生成數據。累計總計算與cumsum功能:

result <- with(dat, by(number, format(date,"%Y"), function(x) c(mean(x),sum(x)))) 
result <- data.frame(names(result), do.call(rbind, result)) 
result <- setNames(cbind(result[-3], cumsum(result[3])), 
        c("year", "average.this.year", "total.to.date")) 

result

year average.this.year total.to.date 
1 1953     9    9 
2 1954    38   47 
3 1956    49   96 
4 1979    32   128 
5 1982    17   145 
6 1985    27   172 
7 1987    22   194 
8 1988    33   227 
9 2005    36   263 
10 2010     4   267