R:基于先前非NA行中的值分配先前的非NA值"n"次

use*_*577 3 r time-series zoo

我有一个数据帧test_case.我在列(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)
)
Run Code Online (Sandbox Code Playgroud)

该变量cutoff指定了我希望将收入中的值"结转"到后续行中的次数(使用包动物园中的na.locf()方法).例如,在上面的数据框中,截止值为2表示收入应该结转两次.

我已经看到关于指定如何在n为常数时使用na.locf进行n次的示例.但在我的情况下,当n正在变化时,我很难概括(R - 将前一次观察向前移动n次).

这是我的原始数据框:

   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
Run Code Online (Sandbox Code Playgroud)

这是所需的输出:

   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
Run Code Online (Sandbox Code Playgroud)

Dav*_*urg 5

这是尝试使用data.table.分组方法是在@jeremys的答案,虽然我正在避免ifelselapply在这里,而是将根据第一个income值复制的第一个income值与NAs值复制.N - (cutoff[1L] + 1L)时间相结合.我也是第一次使用这些值cutoff > 0L)

library(data.table)
setDT(test_case)[which.max(cutoff > 0L):.N, # Or `cutoff > 0L | is.na(income)`
                 income := c(rep(income[1L], cutoff[1L] + 1L), rep(NA, .N - (cutoff[1L] + 1L))), 
                 by = cumsum(cutoff != 0L)]
test_case
#     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
Run Code Online (Sandbox Code Playgroud)