dt_fill raises recycle error all of a sudden

26 views Asked by At

I have data wrangling script, where I just want to fill all NAs with the value above it. I used to do it this way:

library(data.table)
library(tidyfast)

col1 <- c("A", "B", "C", "D")
col2 <- c("X", NA, "Z", NA)

dt <- data.table(col1,
                 col2)

dt[, col2 := dt_fill(dt, col2, .direction = 'down')]

And this always worked, but now I get the error:

Error in `[.data.table`(dt, , `:=`(col2, dt_fill(dt, col2, .direction = "down"))) : 
  Supplied 2 items to be assigned to 4 items of column 'col2'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
1

There are 1 answers

1
s_baldur On

data.table has nafill() which doesn't work for character vectors yet but you can work around that:

nafill2 <- function(x) {
  if      (is.numeric(x)  ) nafill(x, type = "locf")
  else if (is.character(x)) x[nafill(replace(seq_along(x), is.na(x), NA), type = "locf")]
  else                      stop("...")
}

dt[, col2 := nafill2(col2) ]
#      col1   col2
#    <char> <char>
# 1:      A      X
# 2:      B      X
# 3:      C      Z
# 4:      D      Z