Q:

Sum of cells with same row and column name in R

I have a matrix created using table() command in R in which rows and columns do not have same values. 
       0   1   2 
  1    1   2   3  
  2    4   5   6  
  3    7   7   8  

How can I sum the elements with the same row and column name? In this example it is equal to (2+6=)8.

A:

Here's one approach:
# find the values present in both row names and column names
is <- do.call(intersect, unname(dimnames(x)))

# calculate the sum
sum(x[cbind(is, is)])

where x is your table.

