user2284140
user2284140

Reputation: 197

Randomly generate +1 and -1 in a matrix in R

How do I generate +1 and -1 randomly in a matrix of given dimension in R ? For example: For a matrix of size 3*5, the matrix can be:

-1 -1  1  1 -1
 1 -1  1  1  1
-1 -1 -1 -1  1

Upvotes: 0

Views: 85

Answers (1)

Fernando
Fernando

Reputation: 7895

Try

nr = 3 # number of rows
nc = 5 # number of columns
M = matrix(sample(c(-1, 1), nr * nc, replace = TRUE), nrow = nr)
print(M)

     [,1] [,2] [,3] [,4] [,5]
[1,]   -1   -1   -1    1   -1
[2,]    1    1    1   -1   -1
[3,]    1    1    1    1    1

Upvotes: 2

Related Questions