dt_fill 突然引发回收错误

问题描述 投票:0回答:1

我有数据整理脚本,我只想用上面的值填充所有

NA
。我以前就是这样做的:

library(data.table)

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')]

这一直有效,但现在我收到错误:

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.
data.table
1个回答
0
投票

data.table
nafill()
,它不适用于字符向量,但你可以解决这个问题:

nafill2 <- function(x) {
  if (is.numeric(x)) nafill(x, type = "locf")
  else (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
© www.soinside.com 2019 - 2024. All rights reserved.