使用 for 循环创建滞后变量

问题描述 投票:0回答:1

我想要执行的操作: 如果

hmonth=2
hyear=2000
,则从
wageratio.female
hmonth=1
的观测值中减去
hyear=2000
的每个观测值。 如果
hmonth=2
hyear=2001
,则从
wageratio.female
hmonth=1
的观测值中减去
hyear=2001
的每个观测值。 对所有
hmonth
hyear
重复此操作。 创建一个名为
wageratio.lags
的变量来表示差异。

下面是我在

for
循环中尝试的一小部分。我应该使用
for
循环来实现我想要的输出吗?

differences = list()

for i in range(len(hmonth)):
    # Check if the current pair is (2, 2000) or (2, 2001)
    if hmonth[i] == 2:
        if hyear[i] == 2000:
            # Subtract each observation of wageratio_female from that of hmonth=1 and hyear=2000
            difference = wageratio_female[i] - wageratio_female[hmonth.index(1)]
            differences.append(difference)
        elif hyear[i] == 2001:
            # Subtract each observation of wageratio_female from that of hmonth=1 and hyear=2001
            difference = wageratio_female[i] - wageratio_female[hmonth.index(1)]
            differences.append(difference)
Error: unexpected symbol in "for i"

所需输出:

h月 投注比例.女性 投注比率.滞后
1 2000 -0.43 -0.01
1 2001 0.18 -0.62
2 2000 -0.44 0.12
2 2001 -0.44 -0.47
3 2000 -0.32 -0.45
3 2001 -0.91 0.70
4 2000 -0.77 1.24
4 2001 -0.21 不适用
5 2000 0.47 不适用
df <- data.frame(
  wageratio_female = c(-0.43, 0.18, -0.44, -0.44, -0.32, -0.91, -0.77, -0.21, 0.47),
  hmonth = c(1, 1, 2, 2, 3, 3, 4, 4, 5),
  hyear = c(2000, 2001, 2000, 2001, 2000, 2001, 2000, 2001, 2000)
 )
r for-loop dplyr tidyverse
1个回答
0
投票

您可以使用

dplyr
lead/lag
函数来执行此操作,无需循环。例如

library(dplyr)
df %>% 
  group_by(hyear) %>% 
  arrange(hmonth) %>% 
  mutate(diff = lead(wageratio_female) - wageratio_female) %>%
  ungroup()

产生

  wageratio_female     hmonth      hyear    diff
             <dbl> <hvn_lbll> <hvn_lbll>   <dbl>
1            -0.43          1       2000 -0.0100
2             0.18          1       2001 -0.62  
3            -0.44          2       2000  0.12  
4            -0.44          2       2001 -0.47  
5            -0.32          3       2000 -0.45  
6            -0.91          3       2001  0.7   
7            -0.77          4       2000  1.24  
8            -0.21          4       2001 NA     
9             0.47          5       2000 NA 
© www.soinside.com 2019 - 2024. All rights reserved.