How to match and reorder these vectors in R
2
1
Entering edit mode
9.6 years ago
MAPK ★ 2.1k

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 • 5.5k views
ADD COMMENT
4
Entering edit mode
9.6 years ago
Brice Sarver ★ 3.8k

[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"​
ADD COMMENT
0
Entering edit mode

Thank you, this is what I need.

ADD REPLY
3
Entering edit mode
9.6 years ago
raunakms ★ 1.1k
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
    }
}
ADD COMMENT
0
Entering edit mode

Thank you very much

ADD REPLY

Login before adding your answer.

Traffic: 1547 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6