LOCF(Last Observation Carried Forward)

Published by onesixx on

LOCF

zoo :: na.locf(object, na.rm = TRUE, …)

가장 마지막에 나온 값을 이후에도 동일하게 적용한다.
(주의, 맨앞에 NA있는경우 적용할 값이 없어 NA처리가 안됨)

DD <- data.table(Time=c(0,3,4,1,6,18,0,12,13,14), Sth=LETTERS[1:10])
DD[, CycleNo:=NA] 
t_point <- which( c(0,diff(DD$Time))<0 )
DD$CycleNo[1] <- 1

for(i in seq_along(t_point)){
  DD$CycleNo[t_point[i]] <- i+1
}
DD[ , CycleNo:=na.locf(CycleNo, na.rm=FALSE)]
    Time Sth CycleNo             Time Sth CycleNo
 1:    0   A      1           1:    0   A       1
 2:    3   B      NA          2:    3   B       1
 3:    4   C      NA          3:    4   C       1
 4:    1   D              4:    1   D       2
 5:    6   E      NA     =>   5:    6   E       2
 6:   18   F      NA          6:   18   F       2
 7:    0   G              7:    0   G       3
 8:   12   H      NA          8:   12   H       3
 9:   13   I      NA          9:   13   I       3
10:   14   J      NA         10:   14   J       3
cycle <- DD[ , map(.SD, ~ na.locf(.x, na.rm=F)), .SD=c("CycleNo")]
> cycle[[1]]
 [1] 1 1 1 2 2 2 3 3 3 3

NOCB

Next Observed Carried Backward

na.locf( ..., fromLast=T)

cycle <- DD[ , map(.SD, ~ na.locf(.x, na.rm=F)), .SD=c("CycleNo")]
> cycle[[1]]
 [1]  1  2  2  2  3  3  3 NA NA NA
Categories: R Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x