Insert NA values ​​in dataframe

The attached screenshot shows part of the data frame that I just imported into R from an excel file. In cells that are empty, I need to insert "NA". How can I insert an NA into any cell that is empty (leaving already filled cells alone)?

enter image description here

+5
source share
1 answer

The better question is, how can I read it in R since the missing cells will already be NAs.

You may have used something like this:

read.csv(file, header=FALSE,  strip.white = TRUE, sep=",")

Indicate lines NAlike this when you read this:

read.csv(file, header=FALSE,  strip.white = TRUE, sep=",",
    na.strings= c("999", "NA", " ", ""))  

to answer your question. This approach may work:

#making fake data on a Saturday morning
dat <- data.frame(matrix(sample(c("", LETTERS[1:4]), 200, 
    replace=T, c(.6, rep(.1, 4))), 20))

#function to replace blanks with missing
blank2na <- function(x){ 
    z <- gsub("\\s+", "", x)  #make sure it "" and not " " etc
    x[z==""] <- NA 
    return(x)
}

#apply that function
data.frame(sapply(dat,  blank2na))
+16
source

All Articles