Question: (Closed) R programming: concatenate three character vectors
0
gravatar for MAPK
3.3 years ago by
MAPK1.3k
United States
MAPK1.3k wrote:

Hi Guys,

I have three character vectors (final, final2 and final3) of same length. I would like to concatenate  final2 and final 3 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
> 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
> 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 • 1.0k views
ADD COMMENTlink modified 3.3 years ago • written 3.3 years ago by MAPK1.3k

I guess this belongs on SO.

ADD REPLYlink written 3.3 years ago by PoGibas4.7k

I got it figured out, thank you!

ADD REPLYlink written 3.3 years ago by MAPK1.3k

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!

ADD REPLYlink written 3.3 years ago by Giovanni M Dall'Olio26k
1
gravatar for MAPK
3.3 years ago by
MAPK1.3k
United States
MAPK1.3k wrote:

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)
ADD COMMENTlink written 3.3 years ago by MAPK1.3k

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

ADD REPLYlink written 3.3 years ago by Giovanni M Dall'Olio26k
Please log in to add an answer.
The thread is closed. No new answers may be added.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1047 users visited in the last hour