Create a symmetric matrix by specifying upper or lower triangle

Average: 5 (1 vote)

The input is specified as the row-wise lower triangle or column-wise upper triangle.

make.symmetric <- function(values){
	# Values specify row-wise lower triangle or column-wise upper triangle
	# Note:
	#   if length of values isn't triangular, specifically the nth triangular number,
	#   it will fill completely the largest matrix it can and throw the warning
	#   "number of items to replace is not a multiple of replacement length"
	.nth <- floor((sqrt(8*length(values) + 1) - 1) / 2)
	.matrix <- matrix(0, .nth, .nth)
	.matrix[upper.tri(.matrix, diag=TRUE)] <- values
	.matrix <- .matrix + t(.matrix) - diag(diag(.matrix))
	# Could use instead of line above:
	#   .select <- lower.tri(.matrix)
	#   .matrix[.select] <- t(.matrix)[.select]
	.matrix
}