Ordinary matrix product and matrix sum column

I have a TxR sized matrix, and I am looking for a command to execute a row product (return 1 x R product vector). After that I want to sum over the columns, i.e. Summarize R members.

In Matlab, this will be done like this sum (prod (A, 1), 2), but I do not know the code for this in R.

I hope this makes sense.

thanks

+4
source share
2 answers
sum(apply(A, 1, prod))

apply the prod function line by line (1 is the margin), summarize the result.

+8
source

In the database R:

mat <- matrix(c(1,2,3,
                4,5,6,
                7,8,9), byrow = TRUE, ncol = 3)

R <- apply(mat, 1, prod)
R
sum(R)

R> R
[1]   6 120 504
R> sum(R)
[1] 630

CRAN , matrixStats, rowSums, colSums ( ) R.

install.packages("matrixStats") ## install it from CRAN

## load matrixStats
library("matrixStats")
rowProds(mat)

R> rowProds(mat)
[1]   6 120 504
R> sum(rowProds(mat))
[1] 630
+7

All Articles