Search code examples
rsortingrcpp

Reorder a vector by order of another


I have two vectors:

vec1 <- c(0, 1, 2, 3, 4, 5, 6, 7, 9)
vec2 <- c(1, 2, 7, 5, 3, 6, 80, 4, 8)

I would like to set the same order in vec1 as it is in vec2. For example, in vec2 the highest number (position 9) is in position 7, so I would like to put the highest number in vec1 (position 9, number 9) to position 7.

Expected output:

vec1 <- c(0, 1, 6, 4, 2, 5, 9, 3, 7)

I don't have any duplicated values in any vector.

I'm primarily interested in efficient Rcpp solutions but also anything in R is welcome.


Solution

  • We could use rank

    vec1[rank(vec2)]
    #[1] 0 1 6 4 2 5 9 3 7
    

    Or with order

    vec1[order(order(vec2))]
    #[1] 0 1 6 4 2 5 9 3 7
    

    Or as @markus suggested an option with frank from data.table

    library(data.table)
    vec1[frank(vec2)]