[R] Subsetting vector with preserved order

arun smartpink111 at yahoo.com
Fri Jan 3 01:04:50 CET 2014


Hi,
Try ?match
 b[match(d,a)]
#[1] "Joe"  "Bob"  "Dick"
A.K.


I have three vectors as follows: 

> a <- c('A','B','C','D','E') 
> b <- c('Tom','Dick','Harry','Bob','Joe') 
> d <- c('E','D','B') 

Subsetting b by using d on a, with b[a %in% d], gives the names in the order they appear in b: 

>  b[a %in% d] 
> [1] "Dick" "Bob"  "Joe" 

But I'd like them to show in the order in d, as "Joe" "Bob" "Dick". What is the easy way to do this? 

Thanks.



More information about the R-help mailing list