Product of Vector & Data Frame Rows & Columns in R (2 Examples)

In this R tutorial you’ll learn how to compute the product of a vector, and the rows and columns of a data frame.

Example Data

data(iris)                      # Example data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example 1: Get Product of All Vector Elements Using prod() Function

prod(iris$Sepal.Length)         # Product of column vector
# [1] 2.25744e+114

Example 2: Get Product of Numeric Data Frame Rows & Columns

apply(iris[ , 1:4], 2, prod)    # Product of all columns
#  Sepal.Length   Sepal.Width  Petal.Length   Petal.Width 
# 2.257440e+114  1.390618e+72  3.522857e+76  5.945429e-12
apply(iris[ , 1:4], 1, prod)    # Product of all rows
#   [1]   4.9980   4.1160   3.9104   4.2780   5.0400  14.3208   6.5688   5.1000
#   [9]   3.5728   2.2785   5.9940   5.2224   2.0160   1.4190   5.5680  15.0480
#  [17]  10.9512   7.4970  11.0466   8.7210   6.2424  11.3220   3.3120  14.3055
#  [25]   6.2016   4.8000  10.8800   5.4600   4.9504   4.8128   4.7616  11.0160
#  [33]   3.1980   6.4680   4.5570   3.8400   5.0050   2.4696   3.4320   5.2020
#  [41]   6.8250   4.0365   3.6608  16.8000  14.7288   6.0480   6.2016   4.1216
#  [49]   5.8830   4.6200 147.3920 138.2400 157.2165  65.7800 125.5800  93.3660
#  [57] 156.3408  38.8080 114.4572  76.6584  35.0000 111.5100  52.8000 116.4002
#  [65]  76.0032 127.9432 113.4000  64.2060  92.0700  60.0600 163.1232  88.8160
#  [73] 115.7625  96.3312 103.7504 121.9680 127.9488 170.8500 117.4500  51.8700
#  [81]  55.1760  48.8400  73.2888 132.1920 109.3500 146.8800 146.4285  82.8828
#  [89]  89.5440  71.5000  75.5040 117.8520  72.3840  37.9500  82.5552  86.1840
#  [97]  90.2538 100.5082  42.0750  85.0668 311.8500 151.7454 263.9070 184.1616
# [105] 248.8200 316.0080  93.7125 240.0678 174.8700 395.2800 212.1600 174.0096
# [113] 235.6200 142.5000 198.7776 249.6512 193.0500 431.2924 317.7174  99.0000
# [121] 289.4688 153.6640 288.9040 150.0282 264.6567 248.8320 149.9904 161.4060
# [129] 210.7392 200.4480 240.1448 384.2560 220.7744 134.9460 124.3424 324.0930
# [137] 287.8848 196.4160 155.5200 242.5626 279.1488 250.9047 151.7454 295.2832
# [145] 315.0675 240.3960 149.6250 202.8000 261.8136 162.4860

Further Resources & Related Tutorials

Please find some related tutorials on topics such as data objects, vectors, and naming data in the following list.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top