固定值不在列和行上重复 [英] Fixed values not repeated over column and row

查看:85
本文介绍了固定值不在列和行上重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中创建一个矩阵,该矩阵具有一定数量的变量(例如1到10).这些变量应在行和列上随机分配,但BUT不应在任何一个中重复(因此,数字1应该在第1行中一次,在第1列中一次)!

I want to create a matrix in R with a set number of variables (e.g. 1 to 10). Those variables should be randomly assigned over rows and columns BUT should not be repeated in either (so number 1 should be once in row 1 and once in column 1)!

例如:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

但是当然在那个例子中,数字是递增的,我希望它们是随机的.我尝试了简单的矩阵需求,但无法弄清楚该如何做.有人可以帮忙吗?提前致谢!

But of course in that example the numbers are ascending and I want them randomized. I tried simple matrix demands but I cannot figure out how to do this. Can anyone help? Thanks in advance!

推荐答案

除非我对这个问题有误解,否则创建此改组矩阵的方法要简单得多,没有任何循环或复杂的条件语句.

Unless I'm misunderstanding the problem, there's a much simpler way to create this shuffled matrix, without any loops or complicated conditional statements.

# number of rows and columns
n <- 10

# create ordered rows and columns
ordered.by.row <- matrix(1:n, n, n)
ordered.by.col <- matrix(1:n, n, n, byrow = T)

# offset the rows and columns relative to each other.
# no row or column has a repeated value, but the values are still ordered
offset <- (ordered.by.row + ordered.by.col) %% n + 1

# shuffle the columns, then shuffle the rows, this produces a randomized matrix
# 'shuffle.row' is the final, randomized matrix
set.seed(1222) # change this to change randomization
shuffle.col <- offset[,sample(1:n, n, replace = F)]
shuffle.row <- shuffle.col[sample(1:n, n, replace = F), ]

# verify solution
any(apply(shuffle.row, 1, function(r)any(duplicated(r)))) # FALSE
any(apply(shuffle.row, 2, function(r)any(duplicated(r)))) # FALSE

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

这篇关于固定值不在列和行上重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆