R programming
matrix diagonal sum
R coding
data manipulation
programming tutorial

How to sum leading diagonal of table in R

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In R, the leading diagonal of a matrix or table is the set of values running from the top-left corner to the bottom-right corner. Summing it is a common operation in statistics, confusion-matrix analysis, and matrix calculations. The cleanest solution is usually sum(diag(x)), but it helps to understand what diag expects and how to handle non-square inputs safely.

Use diag() on a Matrix

For a square numeric matrix, the shortest and most idiomatic solution is:

r
1m <- matrix(c(
2  4, 1, 2,
3  0, 5, 3,
4  7, 8, 6
5), nrow = 3, byrow = TRUE)
6
7sum(diag(m))

diag(m) extracts the main diagonal, which in this example is 4, 5, and 6. sum(...) then adds those values.

You can verify the intermediate result:

r
diag(m)
# [1] 4 5 6

This is the best default answer when the object is already a numeric matrix.

Table Objects Work Too

R table objects are stored as arrays, so the same idea still works.

r
1counts <- table(
2  actual = c("cat", "cat", "dog", "dog", "dog"),
3  predicted = c("cat", "dog", "dog", "dog", "cat")
4)
5
6counts
7sum(diag(counts))

This is especially useful for confusion matrices, where the leading diagonal often represents correct predictions.

If you are unsure what type you have, you can still inspect it:

r
class(counts)
dim(counts)

As long as the object behaves like a matrix or 2D table, diag can usually pull the diagonal values directly.

Handle Data Frames Carefully

A data frame is not the same thing as a numeric matrix. If the columns are numeric and the shape is appropriate, convert it first.

r
1df <- data.frame(
2  a = c(1, 2, 3),
3  b = c(4, 5, 6),
4  c = c(7, 8, 9)
5)
6
7m <- as.matrix(df)
8sum(diag(m))

This works because the data frame contains only numeric values. If the data frame contains character or factor columns, as.matrix may coerce everything to strings, and then sum will fail or produce nonsense.

A safer check is:

r
all(sapply(df, is.numeric))

If that is FALSE, clean or select the numeric columns before converting.

Non-Square Inputs

The leading diagonal of a rectangular matrix is usually defined up to min(nrow(x), ncol(x)). R’s diag already follows that behavior.

r
1m2 <- matrix(1:12, nrow = 3, byrow = TRUE)
2m2
3diag(m2)
4sum(diag(m2))

Here, the matrix has 3 rows and 4 columns, so the extracted diagonal contains 3 elements.

If you want to be explicit, you can compute the indices yourself:

r
n <- min(nrow(m2), ncol(m2))
sum(m2[cbind(1:n, 1:n)])

This approach is helpful when you want tighter control over indexing or need the same pattern in more customized code.

A Reusable Function

If you do this often, wrap it in a function:

r
1sum_leading_diagonal <- function(x) {
2  if (is.data.frame(x)) {
3    if (!all(sapply(x, is.numeric))) {
4      stop("Data frame must contain only numeric columns.")
5    }
6    x <- as.matrix(x)
7  }
8
9  if (length(dim(x)) != 2) {
10    stop("Input must be a 2D matrix, table, or data frame.")
11  }
12
13  sum(diag(x))
14}
15
16sum_leading_diagonal(m)
17sum_leading_diagonal(counts)

This makes the intent clear and gives you one place to enforce input rules.

Common Pitfalls

The most common mistake is treating a data frame like a numeric matrix without checking column types first. Mixed-type data frames can silently convert to character matrices, which breaks numeric calculations.

Another issue is confusion between the main diagonal and the anti-diagonal. diag(x) always extracts the top-left to bottom-right diagonal, not the other direction.

Some users also assume the matrix must be square. It does not. For rectangular inputs, R takes the diagonal up to the smaller dimension.

Finally, remember that missing values affect the sum. If the diagonal contains NA, use na.rm = TRUE when appropriate:

r
sum(diag(m), na.rm = TRUE)

Summary

  • For matrices and tables in R, sum(diag(x)) is the standard way to sum the leading diagonal.
  • 'table objects work because they behave like arrays.'
  • Convert numeric data frames with as.matrix before using diag.
  • Rectangular matrices are fine; R uses the smaller of row and column counts.
  • Watch for non-numeric data and NA values before summing.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.