Replace all string instances of "NULL" with actual NULL or NA in a data frame

Viewed 204

I wondered if there was a one liner where I could replace all instances of string "NULL" in a DF across multiple fields with just NULL or NA?

exampledf <- data.frame(
  a = c("NULL", "1/1/20", "2/28/20"),
  b = c("NULL", "blah", "ha"),
  c = c("NULL", "NULL", "cat")
)

Is there a one liner that would replace "NULL" across the entire df with NULL or NA?

3 Answers

Using dplyr

library(dplyr)
exampledf <- exampledf %>%
      mutate(across(everything(), na_if, "NULL"))

Just do this:

exampledf[exampledf=="NULL"] <- NA

or with dplyr

exampledf <- exampledf %>% replace(exampledf == "NULL", NA)

We can use replace like below

> replace(exampledf, exampledf == "NULL", NA)
        a    b    c
1    <NA> <NA> <NA>
2  1/1/20 blah <NA>
3 2/28/20   ha  cat
Related