R — Carry last observation forward n times

若如初见. 提交于 2019-11-29 08:16:13

This is not the prettiest thing, but here's how I handle problems like this:

library(data.table)
data <- data.table(data)
data[, rowid:=1:.N, keyby = id]

## flag_a
data[, flag_a_min:=min(rowid[!is.na(flag_a)]), keyby = id]
data[, flag_a_max:=flag_a_min+2]
data[rowid <=flag_a_max & rowid >= flag_a_min, flag_a:=min(na.omit(flag_a))]

## flag_b
data[, flag_b_min:=min(rowid[!is.na(flag_b)]), keyby = id]
data[, flag_b_max:=flag_b_min+2]
data[rowid <=flag_b_max & rowid >= flag_b_min, flag_b:=min(na.omit(flag_b))]

## clean up
data[, c("rowid", "flag_a_min", "flag_a_max", "flag_b_min", "flag_b_max"):=NULL]

> data
    id flag_a flag_b flag_a_desired_output flag_b_desired_output
 1:  1     NA     NA                    NA                    NA
 2:  1     NA     NA                    NA                    NA
 3:  1      1     NA                     1                    NA
 4:  1      1      1                     1                     1
 5:  1      1      1                     1                     1
 6:  1     NA      1                    NA                     1
 7:  1     NA     NA                    NA                    NA
 8:  1     NA     NA                    NA                    NA
 9:  1     NA     NA                    NA                    NA
10:  1     NA     NA                    NA                    NA
11:  2     NA     NA                    NA                    NA
12:  2      1     NA                     1                    NA
13:  2      1     NA                     1                    NA
14:  2      1      1                     1                     1
15:  2     NA      1                    NA                     1
16:  2     NA      1                    NA                     1
17:  2     NA     NA                    NA                    NA
18:  2     NA     NA                    NA                    NA
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!