1

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
  • 17,940
  • 43
  • 142
  • 263

3 Answers3

3

Using dplyr

library(dplyr)
exampledf <- exampledf %>%
      mutate(across(everything(), na_if, "NULL"))
akrun
  • 789,025
  • 32
  • 460
  • 575
2

Just do this:

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

or with dplyr

exampledf <- exampledf %>% replace(exampledf == "NULL", NA)
Elia
  • 1,925
  • 1
  • 5
  • 15
  • 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
  • 80,151
  • 7
  • 17
  • 65