1

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.

Sweepy Dodo
  • 1,761
  • 9
  • 15
  • Sorry, just stumbled across https://stackoverflow.com/questions/16943939/elegantly-assigning-multiple-columns-in-data-table-with-lapply?rq=1 a solution is `lapply(x, \(i) df[get(i) == 'na', (i) := NA ] )` but welcome any other methods – Sweepy Dodo Sep 03 '22 at 12:04
  • Use `lapply`, `.SD` and `.SDcols`; `df[ , (x) := lapply(.SD, function(v) replace(v, v == "na", NA)), .SDcols = x]`. See examples in `?":="`; "## using lapply & .SD" – Henrik Sep 03 '22 at 12:05
  • See also the [vignette](https://cran.r-project.org/web/packages/data.table/vignettes/datatable-reference-semantics.html); e) Multiple columns and `:=`. – Henrik Sep 03 '22 at 12:13
  • Yes, I have used `(x) :=` before. But when confronted with a different problem, this didn't immediately ring any bell Thank you @Henrik and for the vignette link too – Sweepy Dodo Sep 03 '22 at 12:17
  • 1
    Great to hear that it worked the way you wanted! Cheers – Henrik Sep 03 '22 at 12:20

0 Answers0