Reputation: 45
I got a column in a data table from which I would like to replace NAs with 0s. However, the name of that column is dynamic, which means that it's stored in a variable (let's call it x). How do I "select" that one column with its name stored in variable x and replace all its NAs to 0s?
I have tried with no success:
DT[, get(x) := ifelse(is.na(get(x)), 0, get(x))]
DT[, .(x) := ifelse(is.na(.(x)), 0, .(x))]
DT[, x, with = FALSE][is.na(DT[, x, with = FALSE])] <- 0
Upvotes: 0
Views: 91
Reputation: 886938
With data.table
, the correct approach would be to specify the variables in .SDcols
library(data.table)
DT[, (x) := fifelse(is.na(.SD[[1]]), 0, .SD[[1]]), .SDcols = x]
Or another option is to convert to symbol
and then eval
uate
DT[, (x) := fifelse(is.na(eval(as.symbol(x))), 0, eval(as.symbol(x)))]
Or make use of the i
, which is the most efficient approach
DT[is.na(eval(as.symbol(x))), (x) := 0]
DT <- data.frame(a = c(NA, 2, 4, NA, 1), b = 1:5)
setDT(DT)
x <- 'a'
Upvotes: 0
Reputation: 388807
You can use :
library(data.table)
DT[is.na(get(x)), (x) := 0]
DT
# a b
#1: 0 1
#2: 2 2
#3: 4 3
#4: 0 4
#5: 1 5
Other options include :
DT[, (x) := replace(get(x), is.na(get(x)), 0)]
Or
DT[, (x) := ifelse(is.na(get(x)), 0, get(x))]
data
DT <- data.frame(a = c(NA, 2, 4, NA, 1), b = 1:5)
setDT(DT)
x <- 'a'
Upvotes: 2