# Problems when applying rowSums and colSums

Hey there,

I've got a tiny problem with some R-Matrix project that drives me mad. I've created a simplification of the problem and I hope that someone can help me.

So the task is quite simple at first: I want to create the rowSums and the colSums of a matrix and add the sums as elements at the margins of the matrix. My matrix looks like this:

`````` [,1] [,2]
``````

[1,] 1 2
[2,] 3 4

What I want is this:

`````` [,1] [,2] [,3]
``````

[1,] 1 2 3
[2,] 3 4 7
[,3] 4 6 10

My code to reach this goal looks like this:

mat <- matrix(c(1,3,2,4), nrow = 2, ncol = 2)
rowSumx <- rowSums(mat)
colSumx <- colSums(mat)
mat <- rbind(mat, colSumx)
mat <- cbind(mat, rowSumx)

My output, however looks like this:

`````` [,1] [,2] [,3]
``````

[1,] 1 2 3
[2,] 3 4 7
[,3] 4 6 3

What's causing me trouble is the 3 in the bottom right corner. Why does it appear? How do I make it the 10 which would be the correct value both of the sum of rows and the sum of cols?

Kind regards and many thanks in advance

Salvi

It appears the issue occurs because rowSumx is done on the original `mat`.

If you move the `rowSumx` object to just prior to the `cbind` call, then you will get the intended result.

``````mat <- matrix(c(1,3,2,4), nrow = 2, ncol = 2)
colSumx <- colSums(mat)
mat <- rbind(mat, colSumx)
rowSumx <- rowSums(mat)
mat <- cbind(mat, rowSumx)
``````

This results in... 1 Like

Thank you very much!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.