[R] converting blank cells to NAs

David Winsemius dwinsemius at comcast.net
Tue Apr 16 21:56:52 CEST 2013

On Apr 16, 2013, at 6:38 AM, arun wrote:

> Hi,
> I am not sure about the problem.
> If your non-numeric vector is like:
> a,b,,d,e,,f
> vec1<-unlist(str_split(readLines(textConnection("a,b,,d,e,,f")),","))
>  vec1[vec1==""]<- NA
>  vec1
> #[1] "a" "b" NA  "d" "e" NA  "f"
> If this doesn't work, please provide an example vector.
> A.K.
>> Thanks for the response.  That seems to do the trick as far replacing the empty 
> cells with <NA>, however, the problem remains that the vector is 
> not >numeric.  This was the reason I wanted to replace the empty cells 
> with NAs in the first place.  Forcing the vector with as.numeric 
> afterwards doesn't >seem to work either, I get nonsensical results.

In R there are actully multiple version of NA and in hte case of character objects the reserved name is `NA_character_` , ..... not "NA". You can also use `is.na<-`

#Method: `is.na<-`
> vec <- sample(c(letters[1:5], ""), 20, repl=TRUE)
> vec
 [1] "d" "a" "b" ""  ""  ""  "d" "b" "c" "d" ""  "b" "b" "e" ""  "c" ""  ""  "a" "a"
> is.na(vec) <- vec==""
> vec
 [1] "d" "a" "b" NA  NA  NA  "d" "b" "c" "d" NA  "b" "b" "e" NA  "c" NA  NA  "a" "a"

Method: assign NA_character_

> vec <- sample(c(letters[1:5], ""), 20, repl=TRUE)
> vec
 [1] "e" "c" "e" "b" "e" "c" "a" "d" "b" "d" "d" ""  "d" "b" "d" ""  "e" "e" "a" "" 
> vec[vec==""] <-  NA_character_
> vec
 [1] "e" "c" "e" "b" "e" "c" "a" "d" "b" "d" "d" NA  "d" "b" "d" NA  "e" "e" "a" NA 


David Winsemius
Alameda, CA, USA

More information about the R-help mailing list