[R] Preserving order in an intersection

Talbot Katz topkatz at msn.com
Thu Mar 1 21:57:51 CET 2007


Hi.

Here's an odd request that actually arose out of my own bad planning.

Suppose I do the following:

which(v1 %in% v2)

I will get a set of indices for v1, and they will be ordered in the same 
order that v1 is in.  I want the indices of the intersection for v1 ordered 
according to v2.

I do this as follows, and it works in my particular case, although it looks 
like it might not work in general (i.e., if some of the v1 entries are not 
legal as names):

v1io1 = which(v1 %in% v2)
names(v1io1) = v1[v1io1]
v1io2 = v1io1[intersect(v2,v1)]

Is there an easier (or at least easy), reliable way to do this?  Thanks!

--  TMK  --
212-460-5430	home
917-656-5351	cell



More information about the R-help mailing list