[R] paste and NAs

Thomas Lumley tlumley at u.washington.edu
Wed Jul 23 20:49:47 CEST 2003


On Wed, 23 Jul 2003 Benjamin.STABLER at odot.state.or.us wrote:

> I understand how R treats NAs but in the situation below it would be nice to
> have a na.skip argument to paste so it does not convert the NAs to "NA"s and
> simply skips those elements of the vector for pasting.  
> 
> > x
> [1] "2.13" "2.3"  NA     NA     "2.83" NA    
> 
> > paste(x, "0", sep="")
> [1] "2.130" "2.30"  "NA0"   "NA0"   "2.830" "NA0"  
> 
> With na.skip argument:
> 
> paste(x, "0", sep="", na.skip=T)
> [1] "2.130" "2.30"  NA   NA   "2.830" NA  

How about
   ifelse(is.na(x), NA, paste(x,"0",sep=""))

> Otherwise I will use:
> 
> y <- paste(x, "0", sep="")
> gsub(paste("NA","0",sep=""),"", y)
> 
> "" is not the same as NA, but for my purposes "" is close enough.  Why can't
> I use NA as a replacement in gsub, even though c("a", NA) works?
> 


You need to use a character NA. Plain NA is a logical. SO
gsub("NA0",as.character(NA), y)
will work.  This is arguably a bug.

      -thomas


Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle




More information about the R-help mailing list