R滞后于数据帧

R lagging a dataframe

我是 R 的新手,我遇到了延迟操作的问题。

这些是我的数据框。

Stock_Returns

Date          Stock_A       Stock_B    
01.01.1990    NA            NA          
01.02.1990    0.02          0.04        
01.03.1990    0.03          0.05        
01.04.1990    0.04          0.06        

Market_Cap

Date          Stock_A       Stock_B      Sum
01.01.1990    30            30           60
01.02.1990    20            35           55
01.03.1990    30            50           80
01.04.1990    40            60           100

我想要 Stock_Returns 和 Market_Cap 的和积(滞后 -one),然后将它除以 Market_Cap$Sum(滞后 -one)。

这是我的代码,没有延迟!我需要 -1

的延迟
Index <- rowSums(Returns[,2:ncol(Returns)]*(Market_Cap[,3:ncol(Market_Cap)-1]),na.rm=TRUE)/Market_Cap$Sum

我的输出应该是这样的:

Index_Return

Date          Index        
01.01.1990    NA                       
01.02.1990    0.03              
01.03.1990    0.0427           
01.04.1990    0.0525 

1990 年 2 月 1 日的计算结果为 (0.02*30+0.04*30)/60

提前致谢!

这是一种通过使用行号实现所需输出的方法。我们 select 第一个 table 中索引为 n 的行子集,然后是第二个 table 中索引为 n-1 的行子集。

Index <- rowSums(Returns[2:nrow(Returns), 2:ncol(Returns)] * Market_Cap[2:nrow(Returns)-1, 3:ncol(Market_Cap)-1], na.rm = T) / Market_Cap[2:nrow(Returns)-1, "Sum"]

然后我们可以将它追加到Returns:

Returns$Index[2:nrow(Returns)] <- Index