This is a test version of Biostars. For the public version, visit https://www.biostars.org.
R programming: concatenate three character vectors

Hi Guys,

I have three character vectors (final, final2 and final3) of same length. I would like to concatenate final2 and final3 onto final omitting all the NAs in final2 and final3 and get the result as shown below.

I tried something like this, but won't get what I need:

idx2 <- which(!is.na(final2))
idx3<-which(!is.na(final3))
paste(final, final2[idx2], final[idx3], sep=":")

final
  [1] "chr999:9992053031:9992053031-C(34),G()"    "chr999:99933999574:99933999574-C(22),A(2)"   "chr999:115389448:115389448-C(25),A()"
  [4] "chr999:120094925:120094925-A(30),C()"    "chr999:120833042:120833042-C(48),T()"    "chr999:124348684:124348684-C(60),T()"
  [7] "chr999:126686718:126686718-G(18),A()"    "chr999:126691538:126691538-C(9),T()"     "chr999:129913632:129913632-G(28),T()"

final2
  [1] NA     "G(2)" NA     NA     NA     NA

final3
    [1] NA     NA     NA  "T(34)"   NA     NA

result
  [1] "chr999:9992053031:9992053031-C(34),G()"    "chr999:99933999574:99933999574-C(22),A(2),G(2)"   "chr999:115389448:115389448-C(25),A()"
  [4] "chr999:120094925:120094925-A(30),C(),T(34)"    "chr999:120833042:120833042-C(48),T()"    "chr999:124348684:124348684-C(60),T()"
r

I guess this belongs on SO.

I got it figured out, thank you!

Hello MAPK!

We believe that this post does not fit the main topic of this site.

Closed as non-bioinformatics related.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

1 answer

Here is my own answer:

paste2 <- function(...,sep=",") {
  L <- list(...)
  L <- lapply(L,function(x) {x[is.na(x)] <- ""; x})
  gsub(paste0("(^",sep,"|",sep,"$)"),"",
       gsub(paste0(sep,sep),sep,
            do.call(paste,c(L,list(sep=sep)))))
}

final.output<-paste2(final,final2,final3)

Thanks for sharing the solution, although for this type of queries StackExchange is more appropriate.

Log in to answer this question.