【问题标题】:Create new vectors with no element being in the same position as the original vector as well as with other vectors?创建没有元素与原始向量以及其他向量处于相同位置的新向量?
【发布时间】:2019-12-09 12:03:44
【问题描述】:

这个问题是我之前问过的question 的延伸。

假设我有一个向量 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


【解决方案1】:

这是一种方法:

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    相关资源
    最近更新 更多