Reputation: 339
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.
Upvotes: 4
Views: 1562
Reputation: 89097
Another one, self-explanatory:
sum(x[colnames(x)[col(x)] == rownames(x)[row(x)]])
Upvotes: 1
Reputation: 81733
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.
Upvotes: 3