R: convert mutate across character call to data.table

Viewed 104

Apologies if I can't find an original post explaining how to do this tidyverse to data.table conversion.

I would like to mutate across all character vectors replacing <NA> values in character vectors.

How can I translate the following text to data.table?

library(tidyverse)
library(data.table)
mtcars <- mtcars %>% 
  mutate(across(where(is.character), ~na_if(.,"")))
1 Answers

We can use

library(data.table)
nm1 <- names(mtcars)[sapply(mtcars, is.character)]
setDT(mtcars)[, (nm1) := lapply(.SD, function(x) replace(x, x == "", NA)), .SDcols = nm1]
Related