I have a dataframe test_case
. I have missing data in a column (income
).
test_case <- data.frame(
person=c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3),
year=c(2010, 2011, 2012, 2010, 2011, 2012, 2010, 2011, 2013, 2014, 2014, 2014),
income=c(4, 10, 13, NA, NA, NA, 13, NA, NA, NA, NA, NA),
cutoff=c(0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0)
)
The variable cutoff
specifies the number of times that I would like to 'carry forward' the values in income into subsequent rows (using the na.locf() method in the package zoo). For example, in the dataframe above, the value for 2 in cutoff indicates that income should be carried forward twice.
I have seen examples on SO about specifying how to use na.locf to carry forward n times when n is constant. But in my case, I am having trouble generalizing (R -- Carry last observation forward n times) when n is changing.
Here is my original dataframe:
person year income cutoff
1 1 2010 4 0
2 1 2011 10 0
3 1 2012 13 2
4 2 2010 NA 0
5 2 2011 NA 0
6 2 2012 NA 0
7 3 2010 13 3
8 3 2011 NA 0
9 3 2013 NA 0
10 3 2014 NA 0
11 3 2014 NA 0
12 3 2014 NA 0
And here is the desired output:
person year income cutoff
1 1 2010 4 0
2 1 2011 10 0
3 1 2012 13 2
4 2 2010 13 0
5 2 2011 13 0
6 2 2012 NA 0
7 3 2010 13 3
8 3 2011 13 0
9 3 2013 13 0
10 3 2014 13 0
11 3 2014 NA 0
12 3 2014 NA 0