Search code examples
rvectorcomparison

How can I order two vectors in R on the sorting of one?


My question is about the two following vectors:

list_1 <- c(17.5, 19.3, 17.0, 16.5, 19.4, 19.0, 19.6, 20.7, 18.5, 19.0, 20.2, 
             21.0, 19.7, 19.5, 17.0, 20.2, 19.3, 19.6, 19.9, 18.4, 18.6, 19.5)
list_2 <- c(24.5, 24.5, 24.0, 23.9, 25.8, 27.5, 29.1, 26.5, 28.1, 26.5, 
29.2, 30.5, 27.0, 28.5, 25.2, 28.5, 29.1, 29.1, 26.8, 27.8, 26.5, 26.8)

The values in both vectors are correlated, that means that for example 17.5 (list_1) and 24.5 (list_2) belong together.

I want to order list_1 from small to large, and order list_2 relative to the new placement of the value it correlates with in list_1, so keeping 17.5 and 24.5 together on the same placement in both lists.


Solution

  • list_1 <- c(17.5, 19.3, 17.0, 16.5, 19.4, 19.0, 19.6, 20.7, 18.5, 19.0, 20.2, 
            21.0, 19.7, 19.5, 17.0, 20.2, 19.3, 19.6, 19.9, 18.4, 18.6, 19.5)
    list_2 <- c(24.5, 24.5, 24.0, 23.9, 25.8, 27.5, 29.1, 26.5, 28.1, 26.5, 
            29.2, 30.5, 27.0, 28.5, 25.2, 28.5, 29.1, 29.1, 26.8, 27.8, 26.5, 26.8)
    
    df <- data.frame(list_1, list_2)
    
    df <- df[order(df$list_1),]
    
    list2 <- df$list_2
    

    Demo