I have the below table
library(data.table)
df <- data.table(fruit = c('a', 'na')
, price_1 = c('na', 2)
, price_2 = c(2, 'na')
); df
fruit price_1 price_2
1: a na 2
2: na 2 na
I wish to cast values, in specific columns, where they are a string na
to the logical value NA
.
I have tried:
x <- c('fruit', 'price_1')
lapply(x, \(i) df[get(i) == 'na', get(i) := NA ] )
but I get the error:
Error in get(i) : object 'fruit' not found
What am I doing wrong? I am looking for a data.table
method please. Thank you.