To create identity matrix in R, you can use diag() function.

The following method shows how you can do it with syntax.

Method: Use diag() Function

diag(n)

The following example shows how to create identity matrix in R using diag() function.

Using diag() Function

Let’s see how use diag() function to create identity matrix:

# Create identity matrix
ident <- diag(5)

# Print identity matrix
print(ident)

Output:

[,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    0    1    0    0    0
[3,]    0    0    1    0    0
[4,]    0    0    0    1    0
[5,]    0    0    0    0    1

Here the output shows identity matrix of 5X5 whicj created using diag() function.