首页 > 解决方案 > 创建没有元素与原始向量以及其他向量处于相同位置的新向量?

问题描述

这个问题是我之前提出的问题的延伸。

假设我有一个向量 V1(有两个或更多元素):

V1 <- 1:10

我想对一个或多个向量进行采样:

(1)。没有元素与原始向量在同一位置。

(2)。新向量中没有元素位于相同位置。

以下两个是这样的向量:

9  4  7  1  2  5  3 10  6  8
5  7  4  2  3  8  9  6 10  1

标签: r

解决方案


这是一种方法:

#Define the vector
V1 <- 1:10
#Number of rows
n <- 7
#Create a matrix with the vector `V1` in each row
mat <- matrix(V1, ncol = length(V1), nrow = n, byrow = TRUE)
i <- 2

while(i <= n) {
   #Get randomised V1
   temp <- sample(V1)
   #Check if any of the previous row does not have the same combination 
   if (all(colSums(t(t(mat) == temp)) == 0)) {
       #Add the random vector in the matrix
       mat[i, ] <- temp
       i <- i + 1
   }
}

mat
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]    1    2    3    4    5    6    7    8    9    10
#[2,]    4    5    6    7   10    2    1    9    3     8
#[3,]    2    6    7    9    1    3    8   10    5     4
#[4,]    9    3    1    2    4    8    6    5   10     7
#[5,]    7    8    5    3    6    9   10    4    1     2
#[6,]    3    1    4    5    8   10    9    7    2     6
#[7,]    8    4    2   10    9    1    5    6    7     3

推荐阅读