Danielle
Danielle

Reputation: 33

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.

Is this possible? Thanks!

Upvotes: 3

Views: 49

Answers (4)

John Coleman
John Coleman

Reputation: 51998

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.

Upvotes: 0

Jilber Urbina
Jilber Urbina

Reputation: 61154

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

Upvotes: 1

Melissa Key
Melissa Key

Reputation: 4551

Try

n <- 10
m <- matrix(0, nrow = n, ncol = n)
ind <- sample(n^2, 5)
m[ind] <- 1

Upvotes: 1

MKR
MKR

Reputation: 20085

One option is to generate random 5 indexes and replace those in matrix with 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)

Upvotes: 1

Related Questions