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