Skip to content
Prev 247017 / 398506 Next

how to use "apply" function partial to each vector of a matrix

Hello,

Here is one way...

m <- matrix(1:16, nrow=4)
end <- c(2, 3, 1, 3)

ii <- cbind(sequence(end), rep(1:length(end), end))
sums <- tapply(m[ ii ], ii[ , 2], sum)

And here is another way...

sums <- mapply(function(col, lastrow) sum(m[1:lastrow, col]), 1:ncol(m), end)

Hope this helps,
Michael
On 11 January 2011 16:17, zhaoxing731 <zhaoxing731 at yahoo.com.cn> wrote: