alittleboy
alittleboy

Reputation: 10956

calculation of block quantities in a matrix in R

I have a very general question on data manipulations in R, and I am seeking a convenient and fast way. Suppose I have a matrix of dimension (R)-by-(nxm), i.e. R rows and n times m columns.

set.seed(999)
n = 5; m = 10; R = 100
ncol = m*n
mat = matrix(rnorm(n*m*R), nrow=R, ncol=ncol)

Now I want to have a new matrix (call it new.mat) of dimension (R)-by-(m), i.e. given a certain row of mat, I want to calculate a number (say sum) for the first n elements, then a number for the next n elements, and so on. In this way, the first row of mat ends up with m numbers. The same thing is done for every other row of mat.

For the given example above, the 1st element of the 1st row of the new matrix new.mat should be sum(mat[1,1:5]), the 2nd element is sum(mat[1,6:10]), and the last element is sum(mat[1,46:50]). The 2nd row of new.mat is (sum(mat[2,1:5]), sum(mat[2,6:10),...).

If possible, avoiding for loops is preferred. Thank you!

Upvotes: 2

Views: 144

Answers (1)

mnel
mnel

Reputation: 115392

rowsum is a useful function here. You will have to do a bit of transposing to get what you want

You need to create a grouping vector that is something like c(1,1,1,1,1,2,2,2,2,2,....,10,10,10,10,10)

grp <- rep(seq_len(ceiling(ncol(mat)/5)), each = 5, length.out = ncol(mat))
# this will also work, but may be less clear why.
# grp <- (seq_len(ncol(mat))-1) %/%5   

rowsum computes column sums across rows of a numeric matrix-like object for each level of a grouping variable

You are looking for row sums across columns, so you will have to transpose your results (and your input)

 t(rowsum(t(mat),grp))

Upvotes: 4

Related Questions