rreplacena

replace <NA> with NA


I have a data frame containing entries; It appears that these values are not treated as NA since is.na returns FALSE. I would like to convert these values to NA but could not find the way.


Solution

  • The two classes where this is likely to be an issue are character and factor. This should loop over a dtaframe and convert the "NA" values into true <NA>'s but just for those two classes:

    make.true.NA <- function(x) if(is.character(x)||is.factor(x)){
                                      is.na(x) <- x=="NA"; x} else {
                                      x}
    df[] <- lapply(df, make.true.NA)
    

    (Untested in the absence of a data example.) The use of the form: df_name[] will attempt to retain the structure of the original dataframe which would otherwise lose its class attribute. I see that ujjwal thinks your spelling of NA has flanking "<>" characters so you might try this functions as more general:

    make.true.NA <- function(x) if(is.character(x)||is.factor(x)){
                                      is.na(x) <- x %in% c("NA", "<NA>"); x} else {
                                      x}