简体   繁体   English

如何使用指定数量的随机定位1来制作0/1矩阵

[英]How to I make a 0/1 Matrix with a specified number of randomly positioned 1s

I want to make a numeric 10x10 matrix (size is less important) that is filled with 0s and has 1s, but I want there to be only 5 ones and I want them to be randomly assigned so that their position changes every time I run it. 我想制作一个数字10x10矩阵(大小不太重要),填充0并且有1,但我希望它只有5个,我希望它们被随机分配,以便每次运行它们时它们的位置都会改变。

Is this possible? 这可能吗? Thanks! 谢谢!

One option is to generate random 5 indexes and replace those in matrix with 1 . 一种选择是生成随机5索引并用1替换矩阵中的索引。

m[sample(1:100,5,replace = FALSE)] <- 1
m
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    0    1    0    0    0    1    0    0    0     0
# [2,]    0    0    0    0    0    0    0    0    0     0
# [3,]    0    1    0    0    0    0    0    0    0     0
# [4,]    0    0    0    0    0    0    0    0    0     0
# [5,]    1    0    0    0    0    0    0    0    0     0
# [6,]    0    0    0    0    0    0    0    0    0     0
# [7,]    0    0    0    0    0    0    0    0    0     0
# [8,]    0    0    0    0    0    0    0    0    0     0
# [9,]    0    0    0    0    0    0    0    0    1     0
# [10,]    0    0    0    0    0    0    0    0    0     0

Data 数据

m <- matrix(rep(0,100),10)

Try 尝试

n <- 10
m <- matrix(0, nrow = n, ncol = n)
ind <- sample(n^2, 5)
m[ind] <- 1
zero.one <- rep(0, 100)
zero.one[sample(100, 5)] <- 1  # randomly assigning just 5 1's
matrix(zero.one, ncol=10) # creating a 10x10 matrix

Here is a 1-line solution: 这是一个单行解决方案:

matrix(sample(c(rep(1,5),rep(0,95))),nrow = 10)

It randomly shuffles a vector of 5 1s and 95 0s and then converts it to a matrix. 它随机地将5 1s和95 0s的矢量混洗,然后将其转换为矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM