2

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?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299

3 Answers3

4

Using dplyr

library(dplyr)
exampledf <- exampledf %>%
      mutate(across(everything(), na_if, "NULL"))
akrun
  • 874,273
  • 37
  • 540
  • 662
2

Just do this:

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

or with dplyr

exampledf <- exampledf %>% replace(exampledf == "NULL", NA)
Elia
  • 2,210
  • 1
  • 6
  • 18
  • Thanks! Leaving open for a while in case anyone has a tidyverse approach could use within a pipe `exampledf %>%` – Doug Fir May 15 '21 at 16:03
1

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81