Reputation: 197
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
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