在时间序列上向后替换NA的数量有限

时间:2018-11-09 18:15:44

标签: r data.table time-series na zoo

在数据表中,我想在两个方向上进行为期3天的向前和向后的间隙填充过程。

# Example data:
library(data.table)
library(zoo)
dt <- data.table(Value = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.1359223, NA, NA, NA, NA, 0.0000000, 0.0000000, 0.0000000, 0.0000000, 0.0000000, NA))

> dt
           Value 
1:          NA  
2:          NA  
3:          NA  
4:          NA  
5:          NA  
6:          NA  
7:          NA  
8:          NA  
9:          NA  
10:  0.1359223  
11:         NA  
12:         NA  
13:         NA  
14:         NA  
15:  0.0000000  
16:  0.0000000  
17:  0.0000000  
18:  0.0000000  
19:  0.0000000  
20:         NA  

因此,我要创建两列新列,一列用NA向前替换,另一列用向后替换。

# desired output
         Value      forward    backward
1:         NA           NA        NA
2:         NA           NA        NA
3:         NA           NA        NA
4:         NA           NA        NA
5:         NA           NA        NA
6:         NA           NA        NA
7:         NA           NA     0.1359223
8:         NA           NA     0.1359223
9:         NA           NA     0.1359223
10: 0.1359223      0.1359223   0.1359223
11:        NA      0.1359223      NA
12:        NA      0.1359223   0.0000000
13:        NA      0.1359223   0.0000000
14:        NA           NA     0.0000000    
15: 0.0000000      0.0000000   0.0000000
16: 0.0000000      0.0000000   0.0000000
17: 0.0000000      0.0000000   0.0000000
18: 0.0000000      0.0000000   0.0000000
19: 0.0000000      0.0000000   0.0000000
20:        NA      0.0000000          NA

使用以下代码可以很好地进行正向替换:

dt$forward <- NA
r <- rle(is.na(dt$Value))
dt$forward <- na.locf(dt$Value, fromLast = F, na.rm = F)
is.na(dt$forward) <- sequence(r$lengths) > 3 & rep(r$values, r$lengths)

但是我不知道如何修改该代码以进行向后替换。我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:0)

哈克,但是为什么不翻动专栏呢?

代码

# Using your result as basis
dt$Value <- rev(dt$Value)                  
dt$backward <- NA
r <- rle(is.na(dt$Value))
dt$backward <- na.locf(dt$Value, fromLast = F, na.rm = F)
is.na(dt$backward) <- sequence(r$lengths) > 3 & rep(r$values, r$lengths)
dt$Value <- rev(dt$Value)                 
dt$backward <- rev(dt$backward)            

结果

> dt
        Value   forward  backward
 1:        NA        NA        NA
 2:        NA        NA        NA
 3:        NA        NA        NA
 4:        NA        NA        NA
 5:        NA        NA        NA
 6:        NA        NA        NA
 7:        NA        NA 0.1359223
 8:        NA        NA 0.1359223
 9:        NA        NA 0.1359223
10: 0.1359223 0.1359223 0.1359223
11:        NA 0.1359223        NA
12:        NA 0.1359223 0.0000000
13:        NA 0.1359223 0.0000000
14:        NA        NA 0.0000000
15: 0.0000000 0.0000000 0.0000000
16: 0.0000000 0.0000000 0.0000000
17: 0.0000000 0.0000000 0.0000000
18: 0.0000000 0.0000000 0.0000000
19: 0.0000000 0.0000000 0.0000000
20:        NA 0.0000000        NA