我正在尝试按如下方式填充列:
t-1
:if NAV(t-1) - HWM(t-1) >0
然后在t
:HWM(t) = NAV(t)
,否则:HWM(t) = HWM(t-1)
我的R技能非常基础,以下循环虽然有效但却极其缓慢(150,000次观察)
for (i in 1:length(E$HWM)) {
print(i)
HWM[E$t>2][i] <- ifelse( NAV_lag1[E$t>2][i] - HWM_lag1[E$t>2][i] > 0 ,
NAV_lag1[E$t>2][i] ,
HWM_lag1[t>2[i] )
HWM_lag1[i] <-lag(HWM,1)[i]
}
有什么建议让我的流程更有效率?
非常感谢你。
这就是我所拥有的:
zz <- "t NAV HWM NAV_lag1 HWM_lag1
1 1000 NA NA NA
2 1200 1000 1000 NA
3 1400 NA 1200 NA
4 1200 NA 1400 NA
5 1100 NA 1200 NA
5 1000 NA 1100 NA "
以下是我想要的内容:
zz <- "t NAV HWM NAV_lag1 HWM_lag1
1 1000 NA NA NA
2 1200 1000 1000 1000
3 1400 1200 1200 1000
4 1200 1400 1400 1200
5 1100 1400 1200 1400
5 1000 1400 1100 1400"
Data <- read.table(text=zz, header = TRUE)