使用阈值或来自另一个数据框的截止值按列按数据框分组

Group by a data frame by a column using threshold or cutoff from another data frame

我有一个数据框 df_ret,其中包含一只股票的每日 returns 和一个 ID。它是每天,所以这给了我 1762 行。这是从 2010-01-04 到 2016-12-30.

> head(df_ret)
  permno       date         ret  gvkey
1  54594 2010-01-04  0.03437776 001004
2  54594 2010-01-05  0.01935209 001004
3  54594 2010-01-06  0.05035086 001004
4  54594 2010-01-07  0.01571708 001004
5  54594 2010-01-08 -0.01586073 001004
6  54594 2010-01-11 -0.01139941 001004

我有另一个数据框,它也有一个 ID 列,但只有 8 行:


> df_fun
gvkey   datadate fyear fyr       at     sale sich
1 001004 2010-05-31  2009   5 1501.042 1352.151 5080
2 001004 2011-05-31  2010   5 1703.727 1775.782 5080
3 001004 2012-05-31  2011   5 2195.653 2074.498 5080
4 001004 2013-05-31  2012   5 2136.900 2167.100 5080
5 001004 2014-05-31  2013   5 2199.500 2035.000 5080
6 001004 2015-05-31  2014   5 1515.000 1594.300 5080
7 001004 2016-05-31  2015   5 1442.100 1662.600 5080
8 001004 2017-05-31  2016   5 1504.100 1767.600 5080

datadate 列表示会计年度的结束日期。我想要实现的是,我想按财政年度对 df_ret 进行分组并求和 returns,这样我最终也有 8 行。但我想通过使用第二个数据框的 datadate 列作为截止点来做到这一点。显然,我将通过 gvkey 加入两者;或者,我应该先加入然后分组吗?如何?最后,我希望它看起来像:

> df_merged
   gvkey   datadate fyear fyr       at     sale sich return
1 001004 2010-05-31  2009   5 1501.042 1352.151 5080 0.12
2 001004 2011-05-31  2010   5 1703.727 1775.782 5080 0.11
3 001004 2012-05-31  2011   5 2195.653 2074.498 5080 -0.18
4 001004 2013-05-31  2012   5 2136.900 2167.100 5080 0.06
5 001004 2014-05-31  2013   5 2199.500 2035.000 5080 0.22
6 001004 2015-05-31  2014   5 1515.000 1594.300 5080 0.06
7 001004 2016-05-31  2015   5 1442.100 1662.600 5080 -0.12
8 001004 2017-05-31  2016   5 1504.100 1767.600 5080 0.05

感谢任何帮助;非常感谢!

据我了解,您想合并 2 个数据帧,然后过滤以获取相关行,然后在 ret 上使用 ddply 进行分组

library(dplyr)

df_temp <- merge(df_ret,df_fun)
df_temp<-df_temp[ ((df_temp$datadate - df_temp$date)<366)&((df_temp$datadate - df_temp$date)>0),]

df_merged <-ddply(df_temp,c('id', 'weight','fyear','fyr'), summarize,
at=mean(at),
sale=mean(sale), 
sich=mean(sich),
return = prod(1+ret) -1 )