79576815

Date: 2025-04-16 09:29:03
Score: 2
Natty:
Report link

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:

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.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Me too answer (2.5): have the same question
  • Low reputation (0.5):
Posted by: Comevussor