R – Transpose Matrix

To find transpose matrix of a given matrix in R, call t() function [t for transpose], and pass given matrix as argument to it. The function returns the transpose of the supplied matrix.

In this tutorial, we will learn how to transpose a Matrix using t() function, with the help of examples.

Syntax

The syntax of t() function is

</>
Copy
t(x)

where

ArgumentDescription
xA Matrix.

Return Value

t() function returns a matrix.

Examples

In the following program, we will create a matrix A and find Transpose Matrix of A using t() function.

example.R

</>
Copy
data <- c(1, 2, 7, 2, 8, 4, 3, 0, 9)
A <- matrix(data, nrow = 3, ncol = 3)

A_T <- t(A)

print("Matrix A")
print(A)
print("Transpose of A")
print(A_T)

Output

[1] "Matrix A"
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    8    0
[3,]    7    4    9
[1] "Transpose of A"
     [,1] [,2] [,3]
[1,]    1    2    7
[2,]    2    8    4
[3,]    3    0    9

Now, let us take a matrix of different dimensions and find its transpose.

example.R

</>
Copy
data <- c(1, 2, 7, 9, 8, 4, 3, 0)
A <- matrix(data, nrow = 2, ncol = 4)

A_T <- t(A)

print("Matrix A")
print(A)
print("Transpose of A")
print(A_T)

Output

[1] "Matrix A"
     [,1] [,2] [,3] [,4]
[1,]    1    7    8    3
[2,]    2    9    4    0
[1] "Transpose of A"
     [,1] [,2]
[1,]    1    2
[2,]    7    9
[3,]    8    4
[4,]    3    0

We know that transpose of a transpose results in the original matrix. Let us verify that programmatically using t() function.

example.R

</>
Copy
data <- c(1, 2, 7, 9, 8, 4, 3, 0)
A <- matrix(data, nrow = 2, ncol = 4)

A_T_T <- t(t(A))

print("Matrix A")
print(A)
print("Transpose of (Transpose of A)")
print(A_T_T)

Output

[1] "Matrix A"
     [,1] [,2] [,3] [,4]
[1,]    1    7    8    3
[2,]    2    9    4    0
[1] "Transpose of (Transpose of A)"
     [,1] [,2] [,3] [,4]
[1,]    1    7    8    3
[2,]    2    9    4    0

Conclusion

In this R Tutorial, we learned how to Transpose a Matrix in R using t() function, with the help of examples.