簡體   English   中英

按月-年匯總並將類型保留為日期

[英]Aggregate by month-year and keep type as date

我想創建一個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

但是,我的整個方法有點落伍。 有沒有更清潔的方法來獲得所需的輸出?

是的,您可以使其更簡單,並且一勞永逸。 只需在聚合過程中將整個轉換轉換為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中沒有“ Year-Month”日期類型,請參閱此r-faq
  • 您的apply方法不是應如何使用data.table完成此data.table 您只需完成以下操作即可完成最后一步:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM