每个公司每个月的最后观察 (R)

Last observation for each company for each month (R)

我有一个数据框 z,每天有 800 万次观察。对于每家公司(用 seriesid 衡量),我想要当月的最后一个值(如果可用),以及之前(当月内)的总回报和收盘价的值。

我试过使用 z[apply.monthly(z$date,max,by = z$seriesid)],但是这个 returns 只有 NA。其他 apply 尝试只返回一个日期值(因此不与 seriesids 结合)

 date      company totalreturn   close seriesid 
 1: 2018-01-30 x   910.2214 133.375    55860     
 2: 2018-02-06 x   905.9561 132.750    55860     
 3: 2018-02-13 x   900.8377 132.000    55860     
 4: 2018-02-20 x   900.8377 132.000    55860     
 5: 2018-02-27 x   911.0745 133.500    55860     
 6: 2017-03-06 y   921.3112 135.000    55940    
 7: 2017-03-13 y   917.8990 134.500    55940    

理想情况下,数据集将显示为

 date      company totalreturn   close seriesid 
 1: 2018-01-30 x   910.2214 133.375    55860        
 5: 2018-02-27 x   911.0745 133.500    55860         
 7: 2017-03-13 y   917.8990 134.500    55940 

每个公司每月包含一个非 NA 的观测值

我们可以 group_by seriesid 和年月和 select 最后一行 totalreturnclose 都是非 NA 的。

library(dplyr)

df %>%
  group_by(seriesid, month = format(date, "%Y%m")) %>%
  slice(which.max(cumsum(!is.na(totalreturn) & !is.na(close)))) %>%
  ungroup() %>%
  select(-month)


#       date    company totalreturn close seriesid
#      <date>   <fct>         <dbl> <dbl>    <int>
#1    2018-01-30 x              910.  133.    55860
#2    2018-02-27 x              911.  134.    55860
#3    2017-03-13 y              918.  134.    55940

这是假设您的 date 列是日期类型,否则您需要先将其更改为日期 class。


或者使用 base R ave 我们可以做到

df1 <- df[complete.cases(df), ]

df1[unique(with(df1, ave(seq_along(date), seriesid, format(date, "%Y%m"), 
           FUN = function(x) tail(x, 1)))), ]