The details will of course depend on what distribution you’ll want the matrix elements to have, but once you settle on that, you can adapt something like the following:
m <- matrix(sample(1:20, 36, replace=TRUE), nrow=6)
m[lower.tri(m)] <- t(m)[lower.tri(m)]
m
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 19 20 15 6 5 14
# [2,] 20 20 20 3 18 17
# [3,] 15 20 6 5 11 3
# [4,] 6 3 5 6 9 20
# [5,] 5 18 11 9 10 2
# [6,] 14 17 3 20 2 7
For ease of use, you can then wrap up code like that in a function, like so:
f <- function(n) {
m <- matrix(sample(1:20, n^2, replace=TRUE), nrow=n)
m[lower.tri(m)] <- t(m)[lower.tri(m)]
m
}
## Try it out
f(2)
# [,1] [,2]
# [1,] 9 13
# [2,] 13 15
f(3)
# [,1] [,2] [,3]
# [1,] 1 8 3
# [2,] 8 13 5
# [3,] 3 5 14
3
solved How can I generate random real symmetric matrix in R [duplicate]