SoFunction
Updated on 2025-04-10

Method of generating matrix in R language matrix

Mainly introduce the use of matrix functions and rep to generate a matrix

In R language, you can use the matrix() function to create a matrix, and its syntax format is as follows:

  • matrix(data=NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)

The parameters are as follows:

  • data: The element of the matrix is ​​NA by default, that is, if the element value is not given, each item is NA
  • nrow: The number of rows of the matrix, default is 1;
  • ncol: The number of columns of the matrix, default is 1;
  • byrow: Whether the element is filled by row, by column by default;
  • dimnames: row names and column names represented by character vectors.

Rep function is a function that repeats operations in R language

  • rep(x,times,each,)
  • x: represents the object you want to copy, which can be a vector or a factor.
  • times: represents the number of copies, and can only be positive. Negative numbers and NA values ​​are both wrong values. Copy refers to copying the entire vector.
  • each: represents the number of times each element in the vector is copied.
  • : represents the length of the final output vector.

Next, we use these two functions to generate a specific matrix

> matrix(rep(1:4,times = 2),nrow = 4 , ncol = 2 ,byrow =T)
   [,1] [,2]
[1,]  1  2
[2,]  3  4
[3,]  1  2
[4,]  3  4
> matrix(rep(1:4,times = 2),nrow = 4 , ncol = 2 ,byrow =F)
   [,1] [,2]
[1,]  1  1
[2,]  2  2
[3,]  3  3
[4,]  4  4

From the above two execution results, it can be seen that rep generates a row vector, and matrix fills the vector of a row according to the specified fill direction by row nibbling.

Next, we generate a 4x4 matrix, requiring that the elements at each position of the matrix are equal to 1/(i+j-1), and understand the meaning of the two parameters of rep

> I <- matrix(rep(1:4,times = 4),nrow = 4 , byrow = F)
> J <- matrix(rep(1:4,each = 4),nrow = 4 , byrow = T)#J is actually the transposition of I> A <- 1/(I+J-1)
> A
     [,1]   [,2]   [,3]   [,4]
[1,] 1.0000000 1.0000000 1.0000000 1.0000000
[2,] 0.3333333 0.3333333 0.3333333 0.3333333
[3,] 0.2000000 0.2000000 0.2000000 0.2000000
[4,] 0.1428571 0.1428571 0.1428571 0.1428571

This is the end of this article about the method of generating matrix of R language matrix. For more related content of R language matrix matrix, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!