Re: [R] re-ordering a vector by name

About this list Date view Thread view Subject view Author view Attachment view

From: Sundar Dorai-Raj (sundar.dorai-raj@pdf.com)
Date: Sat 08 May 2004 - 07:55:58 EST


Message-id: <409C05EE.3020706@pdf.com>


Liaw, Andy wrote:

> Dear R-help,
>
> Let's say `x1' and `x2' are very long vectors (length=5e5, say) with same
> set of names but in different order. If I want to sort `x2' in the order of
> `x1', I would do
>
> x2[names(x1)]
>
> but the amount of time that takes is quite prohibitive! Does anyone have
> any suggestion on a more efficient way to do this?
>
> If the two vectors are exactly the same length (as I said above), sorting
> both by names would probably be the fastest. However, if the two vectors
> differ in length (and the names for the shorter one are a subset of names of
> the longer one) then that doesn't work...
>
> Best,
> Andy
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

Hi Andy,
   Using match seems to be *much* faster:

R> x1 <- 1:10000; names(x1) <- 1:10000
R> x2 <- 1:10000; names(x2) <- 10000:1
R> system.time(x3 <- x1[names(x2)])
[1] 1.88 0.00 1.88 NA NA
R> system.time(x4 <- x1[match(names(x1), names(x2))])
[1] 0.01 0.00 0.01 NA NA
R> all.equal(x3, x4)
[1] TRUE
R>

This should also work if x1 and x2 are of diffent lengths.

--sundar

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Mon 31 May 2004 - 23:05:08 EST