Given this data.table:
library(data.table)
aa <- data.table(a = c(1, 2, 3), b = c(1, 2, NA), c = c(NA, 2, 3))
What is the better way of replacing NAs in a subset of columns (e.g. only b
), other than
cols = c("b")
aa[, (cols) := {dt <- .SD; dt[is.na(dt)] <- 0; dt}, .SDcols = cols]
I feel like my way is not very clean, there has to be a more readable way. Thanks!
[EDIT]
My first example was not very good, here's a better one:
library(data.table)
aa <- data.table(a = c(1, 2, 3), b = c(1, 2, NA), c = c(NA, 2, 3), d = c(1, NA, 3))
I need to replace NAs in an arbitrary set of columns, e.g. b
and c
. That means I cannot use i
, because matrices are not allowed there.