p <- sample(10L) # a random permutation vector
ip <- invertPerm(p)
s <- signPerm(p)
## 'p' and 'ip' are indeed inverses:
stopifnot(exprs = {
isPerm(p)
isPerm(ip)
identical(s, 1L) || identical(s, -1L)
identical(s, signPerm(ip))
identical(p[ip], 1:10)
identical(ip[p], 1:10)
identical(invertPerm(ip), p)
})
## Product of transpositions (1 2)(2 1)(4 3)(6 8)(10 1) = (3 4)(6 8)(1 10)
pivot <- c(2L, 1L, 3L, 3L, 5L, 8L, 7L, 8L, 9L, 1L)
q <- asPerm(pivot)
stopifnot(exprs = {
identical(q, c(10L, 2L, 4L, 3L, 5L, 8L, 7L, 6L, 9L, 1L))
identical(q[q], seq_len(10L)) # because the permutation is odd:
signPerm(q) == -1L
})
invPerm # a less general version of 'invertPerm'
# \dontshow{
stopifnot(exprs = {
identical(isPerm(0L), FALSE)
identical(signPerm(1:2), 1L)
identical(signPerm(2:1), -1L)
identical(invertPerm(c(3, 1:2)), c(2:3, 1L)) # 'p' of type "double",
tryCatch(invPerm(NA), error = function(e) TRUE) # was a segfault
})
# }
Run the code above in your browser using DataLab