# How to find the row products for each row in an R data frame?

To find the row products for each row in an R data frame, we can use rowProds function of matrixStats package but we need to read the data frame as a matrix.

For Example, if we have a data frame called df then we can find the row products for each row in df by using the command given below −

rowProds(as.matrix(df))

## Example 1

Following snippet creates a sample data frame −

x1<-rpois(20,5)
x2<-rpois(20,2)
x3<-rpois(20,1)
df1<-data.frame(x1,x2,x3)
df1

The following dataframe is created −

 x1 x2 x3
1  3  1  4
2  7  2  0
3  2  4  1
4  9  2  0
5  4  2  2
6  7  3  1
7  5  2  2
8  1  2  0
9  4  1  2
10  4  1  0
11  8  2  0
12  6  2  2
13  6  0  2
14  6  3  1
15  4  2  0
16 10  4  1
17  8  0  0
18  5  4  0
19  6  3  0
20  2  2  0

To load the matrixStats package and to find the row products for data in df1 on the above created data frame, add the following code to the above snippet −

x1<-rpois(20,5)
x2<-rpois(20,2)
x3<-rpois(20,1)
df1<-data.frame(x1,x2,x3)
library(matrixStats)
df2

## Output

If you execute all the above given snippets as a single program, it generates the following Output −

y1  y2  y3  y4 Row_Product_df2
1   0  -1   0   -2              0
2   0  -1  -1    0              0
3   1   0   1    0              0
4   0   0   0    0              0
5   1  -1   1    2             -2
6   0   0  -1   -1              0
7  -1   0  -1    0              0
8   1   0  -1    0              0
9  -2   0  -2    1              0
10  0   0   0    1              0
11 -2   1  -2    0              0
12  0   1   0   -1              0
13  3   0   0    1              0
14  1  -1   1   -2              2
15 -1   1   1   -1              1
16  1   1  -1    0              0
17  0   0  -1    0              0
18  2   0   2   -1              0
19  3   2   0   -1              0
20  1   0  -1   -1              0