1)
下面是一个使用
outer
out <- outer(1:4, 1:4, paste, sep = "-")
out[upper.tri(out)] <- sub("(\\d+)-(\\d+)", "\\2-\\1", out[upper.tri(out)])
out
# [,1] [,2] [,3] [,4]
#[1,] "1-1" "2-1" "3-1" "4-1"
#[2,] "2-1" "2-2" "3-2" "4-2"
#[3,] "3-1" "3-2" "3-3" "4-3"
#[4,] "4-1" "4-2" "4-3" "4-4"
fun <- function(dims, fill = NA) {
mat <- matrix(fill, nrow = dims, ncol = dims)
mat[upper.tri(mat)] <- seq_len(sum(upper.tri(mat)))
pmax(mat, t(mat), na.rm = TRUE)
}
fun(4, fill = 0L)
# [,1] [,2] [,3] [,4]
#[1,] 0 1 2 4
#[2,] 1 0 3 5
#[3,] 2 3 0 6
#[4,] 4 5 6 0