What is the diag() function in R?

Overview

The diag() function in R simply creates a diagonal matrix.

Syntax

The syntax of the diag() function is given below:

diag(x, nrow, ncol)
Syntax for the diag() function

Parameter value

The diag() function takes the following parameter values:

  • x: This is the value that makes the diagonal elements.
  • nrow, ncol: These represent the number of rows and columns that the output matrix should have.

Return value

The diag() function returns a diagonal matrix.

A diagonal matrix is a matrix that has non-zero elements in the diagonal.

Example

# creating the diagonal element
x <- 2
# creating the number of rows the output matrix should have
nrow <- 4
# creating the number of column the output matrix should have
ncol <- 3
# calling the diag() function
mymatrix <- diag(x, nrow, ncol)
# printing the matrix
mymatrix

Explanation

  • Line 2: We create the variable that represents the diagonal element x.
  • Line 5: We create the variable that represents the number of rows of the output matrix nrow.
  • Line 8: We create the variable that represents the number of columns of the output matrix ncol.
  • Line 11: We implement the diag() function on the given variables. The result is assigned to a variable mymatrix.
  • Line 14: We print mymatrix.

Free Resources