Explain the concept of 'Matrices' in 'R' language

 Posted by Niladri.Biswas on 5/1/2013 | Category: Others Interview questions | Views: 1143 | Points: 40
Answer:

A matrix is a two-dimensional array where each element has the same mode (numeric,character, or logical). Matrices are created with the matrix function .

Syntax:

myymatrix <- matrix(vector, nrow=number_of_rows, ncol=number_of_columns,

byrow=logical_value, dimnames=list(char_vector_rownames, char_vector_colnames
))

where
- 'vector' contains the elements for the matrix
- 'nrow' and 'ncol' specify the row and column dimensions
- 'dimnames' contains optional row and column labels stored in character vectors.
- 'byrow' indicates whether the matrix should be filled in by row (byrow=TRUE) or by column (byrow=FALSE). The default is by column.

Below we will see a 5x4 Matrix creation

> y <- matrix(1:20, nrow=5, ncol=4) q

> y
[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20

> cells <- c(1,26,24,68)
> rnames <- c("R1", "R2")
> cnames <- c("C1", "C2") w
> mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=TRUE,
dimnames=list(rnames, cnames))

> mymatrix
C1 C2
R1 1 26
R2 24 68
> mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=FALSE,
dimnames=list(rnames, cnames))
> mymatrix e
C1 C2
R1 1 24
R2 26 68

First, we are creating a 5x4 matrix . Then we create a 2x2 matrix with labels and fill the matrix by rows . Finally, we create a 2x2 matrix and fill the matrix by columns.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response