I am trying to use the colSums and the .colSums function in R to sum different columns of a matrix of different dimensions and store as a vector. These matrices of different dimensions are all part of a larger square matrix. Let me give an example:
mat1 <- matrix(1:9, nrow=3, byrow = TRUE) #this creates a 3x3 matrix as shown below
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Now I want to sum the columns for each row , as in
for row 1, the matrix is of 1x3 dimension and colSums should give (1,2,3) stored as a vector
Now consider row 1 and 2 together. Matrix is of 2x3 dimension and colSums should give (5, 7, 9)
Now consider all three rows. Matrix is of 3x3 dimension and colSums should give (12, 15, 18)
I know how to get the last one:
colsum1 <- colSums(mat1) # this will give colsum1 as (12,15,18)
This also works: colsum1 <- colSums(mat1[, c(1,2]) and returns colsum1 as (12,15)
But I want colSums for only row 1 and all three columns considered (a matrix of 1x3 dimension) and for row 1 and 2 and all three columns (a matrix of 2x3 dimension). Any help would be appreciated. Thanks!
is a great point. One of the untended consequence of the tidyverse is that people miss out on the the powerful expressiveness of base operations on vectors and matrices. In terms of the original problem statement what was sought was vectors
for row 1, the matrix is of 1x3 dimension and colSums should give (1,2,3) stored as a vector
and with subsetting that is very easily done
mat1 <- matrix(1:9, nrow=3, byrow = TRUE)
mat1
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] 4 5 6
#> [3,] 7 8 9
# all columns, all rows
apply(mat1, 2, cumsum)
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] 5 7 9
#> [3,] 12 15 18
# just the vector of all column sums
colSums(mat1)
#> [1] 12 15 18
# just the vector of the first and second column sums
colSums(mat1[,1:2])
#> [1] 12 15
# just the vector the of the second and third column sums
colSums(mat1[,2:3])
#> [1] 15 18
# just the vector of the first and third column sums
colSums(mat1[,c(1,3)])
#> [1] 12 18