2

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(.,"")))
Waldi
  • 39,242
  • 6
  • 30
  • 78
JRR
  • 578
  • 5
  • 21
  • Related reading for the general idea: [Apply a function to every specified column in a data.table and update by reference](https://stackoverflow.com/questions/16846380/apply-a-function-to-every-specified-column-in-a-data-table-and-update-by-referen). – Henrik Jul 30 '21 at 18:07
  • And how to select `data.table` columns by `class`: [How to select only numeric columns from a data table](https://stackoverflow.com/questions/25130531/how-to-select-only-numeric-columns-from-a-data-table) – Henrik Jul 30 '21 at 18:14

1 Answers1

1

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]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Please note that `.SDcols` accepts a function to select the columns. Thus, `.SDcols = is.character` is enough. Cheers – Henrik Jul 30 '21 at 17:52