JoshDG
JoshDG

Reputation: 3931

Leave order intact when extracting from a named vector

So if I have:

>  g<-c(1,5,2,4,6)
> names(g)<-c("josh","daniel","john", "luke", "bill")
> g
  josh daniel   john   luke   bill 
     1      5      2      4      6 
> 
> g[c("john", "daniel", "bill")]
  john daniel   bill 
     2      5      6 

Is it possible to return the values as they are originally ordered in g, i.e. (daniel then john then bill) WITHOUT using a sort function?

Thanks! -Josh

Upvotes: 3

Views: 85

Answers (1)

hatmatrix
hatmatrix

Reputation: 44872

%in% will do this for you:

> g[names(g) %in% c("john", "daniel", "bill")]
daniel   john   bill 
     5      2      6 

Upvotes: 11

Related Questions