This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to match and reorder these vectors in R

Hi guys,

I have R programming question: I have more than 1000 genes names Names. I want to match the samples containing those genes in Names and paste the corresponding gene with the ".AD" extension next to it in the same order to get the Result as shown below. Thank you.

Names <- c("cebi", "pithe", "MAPK", "sapiens", "JUNK", "calli", "STR")
samples <- c("MAPK", "JUNK", "STR")

Result:

"cebi", "pithe", "MAPK", "MAPK.AD", "sapiens", "JUNK", "JUNK.AD", "calli", "STR", "STR.AD"
r

2 answers

[EDIT: you clearly said that order matters; I didn't check back after posting into R. I'll leave this up in case someone can find some utility in it since another has provided an answer that works.]

Wasn't clear if order matters, but here's what you want:

Names <- c("cebi", "pithe", "MAPK", "sapiens", "JUNK", "calli", "STR")
samples <- c("MAPK", "JUNK",  "STR")
names <- Names
samples %in% names
[1] TRUE TRUE TRUE

 match(samples, names)
[1] 3 5 7

 names[match(samples, names)]
[1] "MAPK" "JUNK" "STR"
paste(names[match(samples, names)], ".AD", sep="")
[1] "MAPK.AD" "JUNK.AD" "STR.AD"
c(paste(names[match(samples, names)], ".AD", sep=""), names)
[1] "MAPK.AD" "JUNK.AD" "STR.AD"  "cebi"    "pithe"   "MAPK"    "sapiens"
[8] "JUNK"    "calli"   "STR"
sort(c(paste(names[match(samples, names)], ".AD", sep=""), names))
[1] "calli"   "cebi"    "JUNK"    "JUNK.AD" "MAPK"    "MAPK.AD" "pithe"
[8] "sapiens" "STR"     "STR.AD"​

Thank you, this is what I need.

Names <- c("cebi","pithe","MAPK","sapiens","JUNK","calli","STR")
samples <- c("MAPK","JUNK","STR")

Result <- vector()
count <- 1

for(i in 1:length(Names)){
    index <- which(samples == Names[i])

    if(length(index) == 0){
        Result[count] <- Names[i]
        count <- count + 1
        next
    } else{
        Result[count] <- Names[i]
        count <- count + 1
        Result[count] <- paste(Names[i], ".AD", sep="")
        count <- count + 1
    }
}

Thank you very much

Log in to answer this question.