reorder second double vector according to first do

2019-08-07 14:46发布

问题:

This question relates to: r - reorder second vector according to first. The solution there does not solve the problem when vectors don't start from 1 and have class double.

Given the following two vectors:

a <- c(5.1, 7.2, 4.3, 8.4)
b <- c(4.3, 7.2, 8.4, 5.1)

a third vector c needs be created that would give the order in which vector b needs be reordered for it to be in the same order as a. In this case:

c <- c(4, 2, 1, 3)

such that:

> b[c] == a
[1] TRUE TRUE TRUE TRUE

回答1:

Isn't this c <- match(a, b)?

This can work safely if

  • one vector is a permutation of the other (that is, they are identical if both are sorted);
  • there are no tied values (that is, no value occurs more than once).

Looks like your application meets these requirement, but it is still good for me to point it out for other readers.