Here we create a function, foo
which creates a random vector of 0s and 1s, with only one 1 and the same length as the number of columns of the required matrix. Then, replicate this nrows.
nr <- 6; nc <- 5
foo <- function() sample(c(1, rep(0, nc-1)), nc)
t(replicate(nr, foo()))
Edit: To randomly assign one 1
to each row and one 1
to each column means that the matrix would need to be square. And one way to do this is to use the sparseMatrix
function from the Matrix package.
library(Matrix)
args(sparseMatrix)
# function (i = ep, j = ep, p, x, dims, dimnames, symmetric = FALSE,
# triangular = FALSE, index1 = TRUE, giveCsparse = TRUE, check = TRUE,
# use.last.ij = FALSE)
The i
and j
specify the locations of the non-zero entries of the matrix. So we can specify these using sample(1:n)
where n
is the number of rows and columns of the square matrix.
set.seed(1234) # For reproducibility. Omit in reality.
A <- sparseMatrix(i=sample(1:4), j=sample(1:4))
# 4 x 4 sparse Matrix of class "ngCMatrix"
# [1,] . | . .
# [2,] . . | .
# [3,] | . . .
# [4,] . . . |
Here the |
represent non-zero values (TRUE).
The above matrix A
can be converted into a binary matrix using as.matrix
.
as.matrix(A) * 1
[,1] [,2] [,3] [,4]
[1,] 0 1 0 0
[2,] 0 0 1 0
[3,] 1 0 0 0
[4,] 0 0 0 1