Student1981
Student1981

Reputation: 329

Retrieving a vector from one of its permutations in R-software

In R-software, suppose you have a vector N1 of length n.

n <- 10
N1 <- letters[rbinom(n, size = 20, prob = 0.5)]
names(N1) <- seq(n)

Suppose you have another vector N2 that is a permutation of the elements of N1

N2 <- sample(N1, size = n, replace = FALSE)

I was wondering if you could help me to find a function in R-software that receives N2 as input and obtains N1 as output, please. Thanks a lot for your help.

Upvotes: 0

Views: 36

Answers (1)

r2evans
r2evans

Reputation: 160637

Just a guess:

set.seed(2)
n <- 10
N1 <- letters[rbinom(n, size = 20, prob = 0.5)]
names(N1) <- seq(n)
N1
#   1   2   3   4   5   6   7   8   9  10 
# "h" "k" "j" "h" "n" "n" "g" "l" "j" "j" 

Having repeats makes it difficult to find a return function, since there is not a 1-to-1 mapping. However, if ...

ind <- sample(n)
ind
#  [1]  6  3  7  2  9  5  4  1 10  8
N2 <- N1[ind]
N2
#   6   3   7   2   9   5   4   1  10   8 
# "n" "j" "g" "k" "j" "n" "h" "h" "j" "l" 

We have the same effect that you were doing before, except ...

N2[order(ind)]
#   1   2   3   4   5   6   7   8   9  10 
# "h" "k" "j" "h" "n" "n" "g" "l" "j" "j" 
all(N1 == N2[order(ind)])
# [1] TRUE

This allows you to get a reverse mapping from some function on N2:

toupper(N2)[order(ind)]
#   1   2   3   4   5   6   7   8   9  10 
# "H" "K" "J" "H" "N" "N" "G" "L" "J" "J" 

regardless of whether you have an assured 1-to-1 mapping.

Upvotes: 2

Related Questions