crossprod in R: How to Calculate Cross Product in R

The crossprod() method returns a matrix representing the cross product of x and y, defined as t(x) %*% y, where %*% is matrix multiplication.

crossprod in R

To calculate the cross multiplication in Matrix, use the crossprod() method. The crossprod() is a built-in R function that returns matrix cross-product. If you give matrices x and y as arguments, the crossprod() function returns a matrix cross-product.

Syntax

crossprod(x, y = NULL)

Parameters

x: It is a numeric or complex matrix or vector. Vectors are promoted to single-column or single-row matrices, depending on the context. Missing values (NA) are allowed.

y: It is a numeric or complex vector or matrix. Vectors are promoted to single-column or single-row matrices, depending on the context. The y = NULL is taken to be the same matrix as x. Missing values (NA) are allowed.

Return value

The crossprod() method returns a double or complex matrix.

Calculate cross product of a Matrix in R

To create a matrix in R, use the matrix() function.

data <- matrix(1:9, 3, 3)
cat("The Matrix is: ", "\n")
print(data)

Output

The Matrix is:
     [,1] [,2] [,3]
[1,]   1    4    7
[2,]   2    5    8
[3,]   3    6    9

Now, let’s calculate the cross-product of this matrix.

crossproduct_mat <- crossprod(data)
cat("The product of matrix is: ", "\n")
print(crossproduction_mat)

The output looks like below.

The product of matrix is:
      [,1]   [,2]   [,3]
[1,]   14    32      50
[2,]   32    77     122
[3,]   50   122     194

You can see that we calculated the crossprod of the matrix.

When x or y are not matrices, they are treated as column or row matrices, but their names are usually not promoted to dimnames.

That’s it for this tutorial.

Leave a Comment