How to Apply crossprod & tcrossprod Functions in R (2 Examples)

In this R programming tutorial you’ll learn how to calculate matrix cross products using the crossprod and tcrossprod functions.

Constructing Exemplifying Data

x <- matrix(1:12, nrow = 4)        # Construct matrix in R
x
#      [,1] [,2] [,3]
# [1,]    1    5    9
# [2,]    2    6   10
# [3,]    3    7   11
# [4,]    4    8   12

Example 1: Calculating Cross Product of Matrix Using crossprod() Function

crossprod(x)                       # Cross product
#      [,1] [,2] [,3]
# [1,]   30   70  110
# [2,]   70  174  278
# [3,]  110  278  446

Example 2: Calculating Cross Product of Transposed Matrix Using tcrossprod() Function

tcrossprod(x)                      # Cross product of transposed matrix
#      [,1] [,2] [,3] [,4]
# [1,]  107  122  137  152
# [2,]  122  140  158  176
# [3,]  137  158  179  200
# [4,]  152  176  200  224

Leave a Reply

Your email address will not be published. Required fields are marked *

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