Home > database >  Using for-loop to create a larger matrix w original in it in R?
Using for-loop to create a larger matrix w original in it in R?

Time:03-23

In R, I have a matrix of...

data1 <- c(9,8,7,6,5,4,3,2,1,10,11,12,13,14,15)
matrix_1 <- matrix(data1,nrow=5,ncol=3,byrow=T)

Now that should create the matrix

     [,1] [,2] [,3]
[1,]    9    8    7
[2,]    6    5    4
[3,]    3    2    1
[4,]   10   11   12
[5,]   13   14   15

My goal is to create a 6x4 matrix with that exact matrix for the first 5 rows and 3 columns, then the remaining row and column are sums of the respective row or column, then the single extra spot in the bottom right corner is the total sum of the entire first matrix (matrix_1).

I assume I need to use for loops, but I can't figure out how to get it. Thanks.

I tried messing with the for loop a bit, but I'm stuck on what to sum for that second matrix as well as how to cut the loop at the right point.

CodePudding user response:

R has an apply family (apply, sapply, lapply etc.) that allows you to do stuff without using a for loop.

Here, row sum and column sum are calculated using apply, where 1 in apply(matrix_1, 1, sum) specifies row-wise operation, and 2 specifies column-wise operation. Then rbind and cbind the results to output a 6 x 4 matrix.

rbind(
  cbind(matrix_1, apply(matrix_1, 1, sum)), 
  c(apply(matrix_1, 2, sum), sum(matrix_1))
  )

However, in your case, you don't really need to use apply. You can use rowSums and colSums in base R to do the job.

rbind(
  cbind(matrix_1, rowSums(matrix_1)), 
  c(colSums(matrix_1), sum(matrix_1))
)

Output

     [,1] [,2] [,3] [,4]
[1,]    9    8    7   24
[2,]    6    5    4   15
[3,]    3    2    1    6
[4,]   10   11   12   33
[5,]   13   14   15   42
[6,]   41   40   39  120

CodePudding user response:

Base R has the margintable() convenience function for this. The default returns the sum of all margins of a matrix or array.

addmargins(matrix_1)

             Sum
     9  8  7  24
     6  5  4  15
     3  2  1   6
    10 11 12  33
    13 14 15  42
Sum 41 40 39 120
  • Related