0

I need to replace certain values in my code with NA, using R datatable. The below code only seems to replace one of the values. Does anyone know where I might be going wrong? Thanks

test <- data.table(name=c("x","y"),num1 =c(1.5,444444), num2= c(2020, 9999), num3= c(NA, 666))

numeric_colnames <- c("num1","num2","num3")

test[, (numeric_colnames) := lapply(.SD, function(x) ifelse(x %in% as.numeric(666,9999), as.numeric(NA), x)), .SDcols=numeric_colnames]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
mj2000
  • 13
  • 2

1 Answers1

0

Check the output of as.numeric(666,9999) :

as.numeric(666,9999)
#[1] 666

Hence it is comparing it with only 666. You don't need as.numeric here :

library(data.table)
test<- data.table(name=c("x","y"),num1 =c(1.5,444444), 
                  num2= c(2020, 9999), num3= c(NA, 666))

numeric_colnames<- c("num1","num2","num3")

test[, (numeric_colnames) := lapply(.SD, function(x) 
          ifelse(x %in% c(666,9999), NA, x)), .SDcols=numeric_colnames]
test

#   name     num1 num2 num3
#1:    x      1.5 2020   NA
#2:    y 444444.0   NA   NA
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213