2014-10-30 36 views
0

我想创建data.table的汇总统计信息,按日期列的月份和年份进行汇总。这是我开始:按月份总计并保留日期类型

> head(monthly) 
     betnr persnr idnum frau gebjahr te_med  month tentgelt status 
1: 50536344 62181514 40442 1 1960 76.52142 1993-12-01 0.5777598 fire 
2: 50536344 62744472 40442 0 1963 76.52142 1993-08-01 0.5777598 fire 
3: 50536344 63071749 40442 0 1947 76.52142 1993-12-01 0.5777598 fire 
4: 50536344 63385685 40442 1 1946 76.52142 1993-07-01 0.5777598 fire 
5: 50536344 63918388 40442 0 1952 76.52142 1993-12-01 0.5777598 fire 
6: 50536344 61961225 40442 0 1980 71.90094 1994-12-01 23.1001672 fire 

要创建我的统计,我再运行

statistics2 <- monthly[, list(NOBS = .N, MWAGE=mean(tentgelt)), by=list(status, month=format(month, '%m-%Y'))] 

这将创建正确的统计,但month列现在包含一个字符串。我试图通过固定的日子类型更改为日期是01总是:

x <-apply(statistics2, 1, function(x) paste('01-',x['month'], sep='')) 
statistics2[, month:= as.Date(x, '%d-%m-%Y')] 

这给了我想要的输出:

> head(statistics2) 
    status  month NOBS  MWAGE 
1: hire 1993-01-01 37914 0.5820961 
2: normal 1993-01-01 790 0.5787695 
3: hire 1994-01-01 6471 15.1267445 
4: normal 1994-01-01 23931 22.8101928 
5: hire 1993-02-01 435 0.5946736 
6: normal 1993-02-01 38661 0.5820226 

然而,我的整个做法让人觉得有些土块。有没有更清晰的方法来获得所需的输出?

+0

注意,月,年为_not_日期和这可能就是R不希望它解释为这样的。然而,有一些包装(我现在不记得),它有一个特殊的年 - 月类。 – 2014-10-30 22:25:21

回答

2

是的,你可以更简单,一气呵成。只是整个转换Date类的聚集过程

statistics2 <- monthly[, list(NOBS = .N, 
         MWAGE = mean(tentgelt)), 
         by = list(status, month = as.Date(format(month, '%Y-%m-01')))] 
statistics2 
# status  month NOBS  MWAGE 
# 1: fire 1993-12-01 3 0.5777598 
# 2: fire 1993-08-01 1 0.5777598 
# 3: fire 1993-07-01 1 0.5777598 
# 4: fire 1994-12-01 1 23.1001672 

一些旁注:

  • 正如在他的评论中提到@beginner,没有“年 - 月”日期 键入R,看到这个 r-faq
  • 你的apply方法是不是你应该怎么做与data.table。你可以做简单的完成你的最后一步:

    statistics2[, month := as.Date(paste0("01-", month), "%d-%m-%Y")]