从R软件中的一个排列中检索向量

时间:2022-11-25 19:28:20

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

在R软件中,假设您有一个长度为n的向量N1。

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,它是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.

我想知道你是否可以帮我在R软件中找到一个函数,它接收N2作为输入,并获得N1作为输出。非常感谢你的帮助。

1 个解决方案

#1


2  

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 ...

重复使得很难找到返回函数,因为没有1对1的映射。但是,如果......

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:

这允许您从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.

无论你是否有一个有保证的一对一映射。

#1


2  

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 ...

重复使得很难找到返回函数,因为没有1对1的映射。但是,如果......

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:

这允许您从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.

无论你是否有一个有保证的一对一映射。