suppress NAs in paste()

Eric Fail picture Eric Fail · Dec 2, 2012 · Viewed 37.1k times · Source

Regarding the bounty

Ben Bolker's paste2-solution produces a "" when the strings that are pasted contains NA's in the same position. Like this,

> paste2(c("a","b", "c", NA), c("A","B", NA, NA))
[1] "a, A" "b, B" "c"    ""

The fourth element is an "" instead of an NA Like this,

[1] "a, A" "b, B" "c"  NA     

I'm offering up this small bounty for anyone who can fix this.

Original question

I've read the help page ?paste, but I don't understand how to have R ignore NAs. I do the following,

foo <- LETTERS[1:4]
foo[4] <- NA
foo
[1] "A" "B" "C" NA
paste(1:4, foo, sep = ", ")

and get

[1] "1, A"  "2, B"  "3, C"  "4, NA"

What I would like to get,

[1] "1, A" "2, B" "3, C" "4"

I could do like this,

sub(', NA$', '', paste(1:4, foo, sep = ", "))
[1] "1, A" "2, B" "3, C" "4"

but that seems like a detour.

Answer

IRTFM picture IRTFM · Mar 28, 2013

For the purpose of a "true-NA": Seems the most direct route is just to modify the value returned by paste2 to be NA when the value is ""

 paste3 <- function(...,sep=", ") {
     L <- list(...)
     L <- lapply(L,function(x) {x[is.na(x)] <- ""; x})
     ret <-gsub(paste0("(^",sep,"|",sep,"$)"),"",
                 gsub(paste0(sep,sep),sep,
                      do.call(paste,c(L,list(sep=sep)))))
     is.na(ret) <- ret==""
     ret
     }
 val<- paste3(c("a","b", "c", NA), c("A","B", NA, NA))
 val
#[1] "a, A" "b, B" "c"    NA