find and replace string 'NA' with NA when date-type column is present

Viewed 142

I want to search all columns for 'NA' and replace with NA but running into issues when there is a date column present:

library(lubridate)
x = data.frame(a = c('NA', NA), b = c(today(), today()))
x[x == 'NA'] = NA

returns error:

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

How can I get rid of this? I know the names of the non-date columns, tried to do something like

col = 'a'
x[x == 'NA', col] = NA 

but got the same error.

4 Answers

The error comes from the fact that column b is date type and "NA" cannot be interpreted as a date

x$b == "NA"
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

The code x == "NA" goes through both columns of the dataframe. Try: x$a[x$a == 'NA'] = NA

Maybe you can try replace like below

x$a <- replace(x$a,which(x$a=="NA"),NA)

such that

> x
     a          b
1 <NA> 2020-03-10
2 <NA> 2020-03-10

DATA

x <- structure(list(a = structure(c(NA_integer_, NA_integer_), .Label = "NA", class = "factor"), 
    b = structure(c(18331, 18331), class = "Date")), row.names = c(NA, 
-2L), class = "data.frame")

If we already know the columns that we want to change we can subset those columns, check for "NA" and replace them with NA like :

x[col][x[col] == 'NA'] <- NA
x

#     a          b
#1 <NA> 2020-03-11
#2 <NA> 2020-03-11

Or to be very specific :

x[col][x[col] == 'NA' & !is.na(x[col])] <- NA

This seems to work with your reprex:

na_func <- function(x) gsub('NA', NA,x)
x[1] <- as.data.frame(lapply(x[1], na_func))
Related