Generating inverse permutation

后端 未结 2 602
执念已碎
执念已碎 2021-01-11 11:28

Suppose we are given a vector foo and we have to temporarily permute it (sort or re-order it), compute some vector bar on the base

2条回答
  •  -上瘾入骨i
    2021-01-11 11:51

    This will work, because [order(o)] inverts the action of [o]:

    foo <- c(1, 7, 3, 5, 2)
    o <- order(foo)
    
    (foo[o]*2)[order(o)]
    # [1]  2 14  6 10  4
    

    To show that it works more generally:

    testAlgorithm <- function(foo) {
        o <- order(foo)
        identical(foo, foo[o][order(o)])
    }
    
    x <- c(1, 7, 3, 5, 2)
    y <- c(1,2,5,7,4, 99, 88, 3, 0)
    z <- sample(1000)                  ## (No ties)
    zz <- sample(1000, replace=TRUE)   ## (Many ties)
    all(sapply(list(x,y,z,zz), testAlgorithm))
    [1] TRUE
    

提交回复
热议问题