Matrices in R

In this recipe, we will dive into R's capability with regard to matrices.

Matrices in R

How to do it…

A vector in R is defined using the c() notation as follows:

vec = c(1:10)

A vector is a one-dimensional array. A matrix is a multidimensional array. We can define a matrix in R using the matrix() function. Alternatively, we can also coerce a set of values to be a matrix using the as.matrix() function:

mat = matrix(c(1,2,3,4,5,6,7,8,9,10),nrow = 2, ncol = 5)
mat

To generate a transpose of a matrix, we can use the t() function:

t(mat) # transpose a matrix

In R, we can also generate an identity matrix using the diag() function:

d = diag(3) # generate an identity ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.