R language learning Basic knowledge of matrices and arrays

Today's notes cover the basics of matrices and arrays in the R language.

R language matrix

Create a matrix

The matrix can be numbers, symbols, and mathematical expressions, similar to a common two-dimensional array, a matrix m×n with m rows (row) and n columns (col).

Matrices in R language can be created using the matrix() function. The syntax is as follows:
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,dimnames = NULL)

Parameter Description:

  • data vector, matrix of data
  • nrow number of rows
  • ncol number of columns
  • byrow logical value, FALSE by column, TRUE by row
  • dimname sets the row and column names. This parameter consists of a list of two vectors (strings).
> # Create a matrix by row arrangement
> zhen_1 = matrix(c(1:12),nrow = 3,byrow = TRUE)
> print(zhen_1)
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12
> # Define row and column names
> rownames_1 = c("a1","a2","a3")
> colnames_2 = c("b1","b2","b3","b4")
> # output matrix
> out_1 = matrix(c(1:12),nrow = 3,byrow = TRUE,dimnames = list(rownames_1,colnames_2))
> print(out_1)
   b1 b2 b3 b4
a1  1  2  3  4
a2  5  6  7  8
a3  9 10 11 12

transpose matrix

The R language matrix provides the t() function, which can realize the exchange of rows and columns of the matrix. The change effect is as follows:

We transpose the out_1 matrix we just created and output it as follows:

> out_1 = matrix(c(1:12),nrow = 3,byrow = TRUE,dimnames = list(rownames_1,colnames_2))
> print(out_1)
   b1 b2 b3 b4
a1  1  2  3  4
a2  5  6  7  8
a3  9 10 11 12
> print(t(out_1))  #Output transposed matrix with t()
   a1 a2 a3
b1  1  5  9
b2  2  6 10
b3  3  7 11
b4  4  8 12

call matrix element

The column index and row index of the element can be obtained, similar to the coordinate form, to obtain the matrix elements, as follows:

> print(out_1) #get the entire matrix
   b1 b2 b3 b4
a1  1  2  3  4
a2  5  6  7  8
a3  9 10 11 12
> print(out_1[1,2]) # Get the element at row 1 and column 2
[1] 2
> print(out_1[2,]) # Get the element of row 2
b1 b2 b3 b4 
 5  6  7  8 

Matrix calculation

Most people have learned linear algebra and understand the rules of addition, subtraction, multiplication and division of matrices. It is worth noting that addition and subtraction can only be performed on matrices with the same number of rows and columns. Only the number of columns of the first matrix is ​​equal to the rows of the second matrix. Numbers can be multiplied together. Next is the demonstration:

> # To add and subtract matrices, just change the plus sign to a minus sign
> out_sum = m_1 + m_2  # Both matrices are 2x3
> cat("result:","\n")
result: 
> print(out_sum)
     [,1] [,2] [,3]
[1,]   14   -2    4
[2,]   18    8    6
> # matrix multiplication
> out_cheng = m_1 * m_2  
> cat("result:","\n")
result: 
> print(out_cheng)
     [,1] [,2] [,3]
[1,]   49    1    4
[2,]   81   16    9
> # matrix division
> out_chu = m_1 / m_2  
> cat("result:","\n")
result: 
> print(out_chu)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1

array

The R language can create one-dimensional or multi-dimensional arrays. An array is a collection of the same type, and a matrix is ​​a two-dimensional array.


Arrays are created using the array() function, which takes a vector as an input parameter, and dim can be used to set the array dimensions. The syntax format is as follows:

array(data = NA, dim = length(data), dimnames = NULL)

  • data vector, array element.
  • The dimension of the dim array, the default is a one-dimensional array.
  • dimnames dimension names, must be a list

For example, to create a 3×3 two-dimensional array for subsequent demonstrations, the method is as follows:

> v1 = c(1,2,3)
> v2 = c(4,5,6,7,8,9)
> shuzu = array(c(v1,v2),dim = c(3,3,2))
> print(shuzu)
, , 1

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
  • Set the name of each dimension

    > column.names = c("col1","col2","col3")  #set column names
    > row.names = c("row1","row2","row3") #set row name
    > matrix.names = c("m1","m2") #set matrix name
    > out_3 = array(c(v1,v2),dim = c(3,3,2),dimnames = list(row.names,column.names,matrix.names)) #set array name
    > print(out_3) #output
    , , m1
    
       col1 col2 col3
    row1    1    4    7
    row2    2    5    8
    row3    3    6    9
    
    , , m2
    
       col1 col2 col3
    row1    1    4    7
    row2    2    5    8
    row3    3    6    9
    #The above m1 and m2 matrices should be used in the demonstration later in the note and will not be repeated
  • access array elements

The elements of the array have coordinate positions, and the index order is (row, column, dimension).

, , m2  #the second matrix

     col1 col2 col3
row1    1    4    7
row2    2    5    8
row3    3    6    9

> print(out_3[3,1,2])
[1] 3  #The output is correct
  • Manipulate array elements

Arrays can be accessed by accessing the elements of the matrix, such as creating a new matrix from a matrix in the array, and then performing matrix addition and subtraction operations, as demonstrated below:

> matrix_1 = shuzu[,,1] 
> matrix_2 = shuzu[,,2]
> sum_1 = matrix_1 + matrix_2
> print(sum_1)
     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18

The apply() function can calculate across dimensions of an array. The syntax format is: apply(x, margin, fun)

  • x array
  • margin data name (1 for row, 2 for column, c(1,2) for row and column)
  • fun calculation function
> print(shuzu)  
, , 1   #the first matrix of the array
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

, , 2  #the second matrix of the array
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> out_4 = apply(shuzu,1,sum)  #Sums all matrices of an array on a per-row basis
> print(out_4)
[1] 24 30 36  #The first line of data is 24=1+4+7+1+4+7, it really works!
Quick memory:
# Calculates the sum of the numbers corresponding to the rows of all matrices in an array
result <- apply(shuzu, c(1), sum)
# Calculates the sum of the numbers in the corresponding columns of all matrices in an array
result <- apply(shuzu, c(2), sum)
# Calculate the sum of all numbers inside each matrix in an array
result <- apply(shuzu, c(3), sum)

References:
https://www.runoob.com/r
Public number: Shengxin analysis notes

This article is by mdnice Multi-platform release

Tags: Back-end

Posted by luked23 on Tue, 20 Sep 2022 23:03:26 +0530