None of the above answers are satisfactory. My guess is that many beginners in R would have the same question and they deserve a clear and complete answer.
In maths, the trace of a matrix is defined only for squared matrix and the canonical way to compute the trace of a matrix in R is
sum(diag(x))
In particular:
stats:::Tr()
.matrix.trace()
of the package matrixcalc
has no added value.tr()
of the package psych
is, as described by the authors, doing exactly sum(diag())
.sum(diag())
are clear in this matter.It is therefore strongly recommended to stick with sum(diag())
which is simple and efficient even for very large matrices. sum()
is a primitive function and the complete code of diag()
is available here.