简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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