r - 创建没有元素与原始向量以及其他向量处于相同位置的新向量?
问题描述
这个问题是我之前提出的问题的延伸。
假设我有一个向量 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
解决方案
这是一种方法:
#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
推荐阅读
- javascript - HTML DataTables 在单元格中呈现函数
- vba - 错误 5854 - 字符串参数太长?
- ruby-on-rails - 使用 Trix 在文本中嵌入变量
- html - 删除移动设备上形状分隔符中出现的线条
- sitefinity - sitefinity form populate dropdownlist from API
- flutter - 如何在 ListView 中滚动
- java - Java Swing 如何在 JTextFields 上定义多个焦点侦听器但具有不同的按钮操作
- mysql - 驱动程序发生异常:SQLSTATE[HY000] [2002] Operation Now In Progress
- amazon-web-services - Quorum 节点使用 docker-compose 运行良好,但在 kubernetes 上部署时崩溃
- javascript - Javascript用数组中的日期和0计数填充缺失的日期