0

With data.table, I have a column with many NA, I would like to replace the NA's with prior non-NA value. I can shift to prior one at certain place, but can't really locate on the nearest prior one. Please advice, and here is the toy example.

x <- data.table(A = 1:5, B.1 = c(1,NA,NA,2,NA), B.2 = c(1,1,1,2,2))
x[,B.3 := ifelse(is.na(B.1), shift(B.1, 1), B.1)]

#   A B.1 B.2  B.3
#1: 1   1   1  1
#2: 2  NA   1  1
#3: 3  NA   1 NA
#4: 4   2   2  2
#5: 5  NA   2  2

B.1 is my target column, and B.2 is what I wanna get. As you can see, x$B.1[2] is following x$B.1[1], x$B.1[3] also follows x$B.1[1], since x$B.1[1] is the nearest prior non-NA value. So, my attention is to make B.2, but I only can do B.3.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Grec001
  • 1,111
  • 6
  • 20
  • 1
    `x[, (cols) := lapply(.SD, zoo::na.locf), .SDcols = cols]` where `cols` are the columns you want to fill values. – Ronak Shah Jun 07 '19 at 11:47
  • many thanks! I will check, and will remove the question. Thanks! – Grec001 Jun 07 '19 at 11:58
  • 1
    No need to remove the question you can keep it. It might help somebody else using different search term coming to this post. – Ronak Shah Jun 07 '19 at 12:04
  • 2
    @RonakShah In `data.table >= 1.12.3` you can use `nafill` or `setnafill` (see [my answer in the linked post](https://stackoverflow.com/a/55764998/1851712)). – Henrik Jun 07 '19 at 12:12
  • @Henrik WOW, amazing data.table, just not too long ago, we were at 1.10, then comes the 1.12.2, now comes to 1.12.3!!! – Grec001 Jun 07 '19 at 13:24

0 Answers0