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

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 #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 #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 #calculate dot product between vectors
dot(a, b)

[1] 35```

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

Additional Resources

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