0

Let's say I have this dataset:

library(data.table)
comb <- CJ(1:4, 2005:2008) 
comb$var3 <- c(1, NA, 2, NA, 3, NA, 4, NA, 5, NA, 6, NA, 7, NA, 8, NA)

I want to fill the NAs according to the previous value. For instance, I want for Id 1 & year 2006 the value 1. For 2008 the value 2. The same for the other IDs. In the end the dataset should look like this:

library(data.table)
comb <- CJ(1:4, 2005:2008) 
comb$var3 <- c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8)

How can I achieve it?

1 Answers1

1

We can use na.locf

library(zoo)
comb[, var3 := na.locf(var3)]
comb
#    V1   V2 var3
# 1:  1 2005    1
# 2:  1 2006    1
# 3:  1 2007    2
# 4:  1 2008    2
# 5:  2 2005    3
# 6:  2 2006    3
# 7:  2 2007    4
# 8:  2 2008    4
# 9:  3 2005    5
#10:  3 2006    5
#11:  3 2007    6
#12:  3 2008    6
#13:  4 2005    7
#14:  4 2006    7
#15:  4 2007    8
#16:  4 2008    8

Based on the example, the following should also work

comb[, var3 := cumsum(!is.na(var3))]
akrun
  • 874,273
  • 37
  • 540
  • 662