How to find the row product of a matrix in R?


To find the row product of a matrix in R, we can use apply function along with prod function. For example, if we have a matrix called M then to find the row product of a matrix we can use the command apply(M,1,prod). We need to remember that the output will be a vector not matrix. Check out the below examples to understand how to perform the row product of the matrix.

Example

Consider the below matrix −

 Live Demo

M1<-matrix(rpois(40,5),ncol=2)
M1

Output

    [,1] [,2]
[1,]  2    7
[2,]  5    5
[3,]  4    6
[4,]  6    8
[5,]  9    4
[6,]  5    8
[7,]  6    4
[8,]  5    4
[9,]  6    4
[10,] 6    8
[11,] 6    8 
[12,] 9    5
[13,] 2    5
[14,] 3    3
[15,] 10   9
[16,] 3    4
[17,] 5    7
[18,] 5    8
[19,] 6    3
[20,] 5    9

Finding row product for matrix M1 −

Example

apply(M1,1,prod)

Output

[1] 14 25 24 48 36 40 24 20 24 48 48 45 10 9 90 12 35 40 18 45

Example

 Live Demo

M2<-matrix(rpois(40,1),ncol=2)
M2

Output

    [,1] [,2]
[1,]  2   0
[2,]  0   0
[3,]  1   0
[4,]  1   2
[5,]  0   1
[6,]  3   1
[7,]  1   1
[8,]  3   2
[9,]  0   2
[10,] 2   0
[11,] 0   1
[12,] 1   0
[13,] 2   0
[14,] 0   1
[15,] 0   1
[16,] 0   2
[17,] 3   1
[18,] 2   3
[19,] 0   1
[20,] 2   1

Finding row product for matrix M2 −

Example

apply(M2,1,prod)

Output

[1] 0 0 0 2 0 3 1 6 0 0 0 0 0 0 0 0 3 6 0 2

Example

 Live Demo

M3<-matrix(round(rnorm(40,1,0.5),1),ncol=2)
M3

Output

    [,1]  [,2]
[1,] 1.1   0.2
[2,] 1.5   1.2
[3,] 1.4   0.7
[4,] 1.6   1.4
[5,] 1.4   0.2
[6,] 1.1   1.0
[7,] 0.6   0.9
[8,] 1.5   1.5
[9,] 0.5  -0.1
[10,] 1.3  0.4
[11,] 0.4  0.7
[12,] 1.3  1.1
[13,] 1.3  0.5
[14,] 0.5  0.6
[15,] 0.9  0.4
[16,] 0.8  0.8
[17,] 0.7  0.3
[18,] 0.3  1.7
[19,] 1.5  0.9
[20,] 0.4  2.2

Finding row product for matrix M3 −

Example

apply(M3,1,prod)

Output

[1] 0.22 1.80 0.98 2.24 0.28 1.10 0.54 2.25 -0.05 0.52 0.28 1.43
[13] 0.65 0.30 0.36 0.64 0.21 0.51 1.35 0.88

Updated on: 16-Mar-2021

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements