How to Calculate the Dot Product in R (With Examples)


Given vector a = [a1, a2, a3] and vector b = [b1, b2, b3], the dot product of vector a and vector b, denoted as a · b, is given by:

a · b = a1 * b1 + a2 * b2 + a3 * b3

For example, if a = [2, 5, 6] and b = [4, 3, 2], then the dot product of a and b would be equal to:

a · b = 2*4 + 5*3 + 6*2

a · b = 8 + 15 + 12

a · b = 35

In essence, the dot product is the sum of the products of the corresponding entries in two vectors.

How to Calculate the Dot Product in R

There are two ways to quickly calculate the dot product of two vectors in R:

Method 1: Use %*%

The following code shows how to use the %*% function to calculate the dot product between two vectors in R:

#define vectors
a <- c(2, 5, 6)
b <- c(4, 3, 2)

#calculate dot product between vectors
a %*% b

     [,1]
[1,]   35

The dot product turns out to be 35.

Note that this function works for data frame columns as well:

#define data
df <- data.frame(a=c(2, 5, 6),
                 b=c(4, 3, 2))

#calculate dot product between columns 'a' and 'b' of data frame
df$a %*% df$b

     [,1]
[1,]   35

Method 2: Use the dot() function

We can also calculate the dot product between two vectors by using the dot() function from the pracma library:

library(pracma)

#define vectors
a <- c(2, 5, 6)
b <- c(4, 3, 2)

#calculate dot product between vectors
dot(a, b)

[1] 35

Once again, the dot product between the two vectors turns out to be 35.

Related: How to Calculate a Cross Product in R

Additional Resources

The following tutorials explain how to calculate a dot product using other statistical software:

How to Calculate the Dot Product in Excel
How to Calculate the Dot Product in Google Sheets
How to Calculate the Dot Product on a TI-84 Calculator

Leave a Reply

Your email address will not be published.