To calculate the dot product in R, you can use three different methods. The dot product is basically multiplication of vectors.

The following methods show how you can do it with syntax.

Method 1: Use %*% Operator

a %*% b

Method 2: Use sum() and * operator

sum (a * b)

Method 3: Use dot() Function from pracma Package

library(pracma)

dot(a, b)

The following examples shows how to use all this methods to calculate dot product in R.

Use %*% Operator

Let’s see how we can calculate dot product using %*% operator:

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)

# Calculate dot product
a%*%b

Output:

      [,1]
[1,] 32755

Here the output shows dot product of two vectors which calculated using %*%.

Use sum() and * Operator

Let’s use sum() function and * operator to calculate the dot product of vectors:

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)

# Calculate dot product                 
d <- sum(a * b)

# Print dot product
print(d)

Output:

[1] 32755

The output shows dot product of vectors that we declared in above code.

Use dot() Function from pracma Package

You can use dot() function from pracma package to calculate dot product in R:

# load library
library("pracma")

# Define vectors
a <-c(78,85,89,96,74,75)
b <-c(65,66,64,69,70,61)

# Calculate dot product                 
dot(a,b)

Output:

[1] 32755

Here in the above code we calculated dot product using dot() function.