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

标签 r dataframe panel xts

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

我试过使用 z[apply.monthly(z$date,max,by = z$seriesid)],但是这只返回 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 和 year-month 并为 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 列是 Date 类型,否则您需要先将其更改为 Date 类。


或者使用 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)))), ]

关于r - 每个公司每个月的最后观察 (R),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933064/

相关文章:

r - 两个 data.table 的连接失败

r - 如何在没有for循环的情况下连接矩阵的列重复

r - 如何检查 data.table 键是否正常工作以及为什么不能正常工作?

R:根据对特定行进行分组来创建包含值的列

python - 根据 Pandas 中的关键字对列进行分区

GWT 在页面/面板之间滑动

r - 将 R htmlwidget 嵌入现有网页

python - Pandas 数据框中的行操作

java - 在控制面板 Java Applet 中拥有多个 JRE 的用户

java - 如何制作 Netbeans 的桌面 Pane