Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 202012

Imputing NA with conditional LOCF

$
0
0

I'm stucked with a variation of a general problem. I have this situation, partially resolved by the code provided below.

ID Ins  Y
1   0 2010
1  NA 2011
1   1 2012
1  NA 2013
1  NA 2014
2   0 2011
2   0 2012
2  NA 2013
3  NA 2010
3   0 2011
3   0 2012
4   0 2010
4  -1 2011
4  NA 2012
5  NA 2012
5  -1 2013
5   0 2014

And I would like to impute NAs with LOCF approach and get Ins_b:

ID Ins  Y    Ins_b
1   0 2010     0
1  NA 2011    NA
1   1 2012     1
1  NA 2013     1
1  NA 2014     1
2   0 2011     0
2   0 2012     0
2  NA 2013    NA
3  NA 2010    NA
3   0 2011     0
3   0 2012     0
4   0 2010     0
4  -1 2011    -1
4  NA 2012    NA
5  NA 2012    NA
5  -1 2013    -1
5   0 2014     0

Basically, I need to keep NAs, if there any, when previous values of my Ins variable are 0, and replace NAs with 1 if missingness occurs after the first appearance of 1 in my Ins variable. Now -1 should remain -1.

Thanks for your suggestions so far, much appreciated.


Viewing all articles
Browse latest Browse all 202012

Trending Articles