Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert NA values into dataframe blank cells when importing read.csv/read.xlsx

Tags:

r

excel

na

read.csv

The attached screenshot shows part of a dataframe which I have just imported into R from an excel file. In the cells which are blank, I need to insert 'NA'. How can I insert NA into any cell which is blank (whilst leaving the already populated cells alone)?

enter image description here

like image 822
luciano Avatar asked Aug 04 '12 15:08

luciano


1 Answers

The better question is how can I read it into R so the missing cells will already be NAs.

Maybe you used something like this:

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

Specify the NA strings like this when you read it in:

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

to actually answer your question. This approach could 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's "" and not " " etc
    x[z==""] <- NA 
    return(x)
}

#apply that function
data.frame(sapply(dat,  blank2na))
like image 178
Tyler Rinker Avatar answered Nov 13 '22 18:11

Tyler Rinker