- R Data Visualization Cookbook
- Atmajitsinh Gohil
- 310字
- 2021-08-06 19:21:06
Matrices in R
In this recipe, we will dive into R's capability with regard to matrices.

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 matrix
We can nest the rep ()
function within matrix()
to generate a matrix with all zeroes as follows:
zro = matrix(rep(0,6),ncol = 2,nrow = 3 )# generate a matrix of Zeros zro
How it works…
We can define our data in the matrix ()
function by specifying our data as its first argument. The nrow
and ncol
arguments are used to specify the number of rows and column in a matrix. The matrix
function in R comes with other useful arguments and can be studied by typing ?matrix
in the R command window.
The rep()
function nested in the matrix()
function is used to repeat a particular value or character string a certain number of times.
The diag()
function can be used to generate an identity matrix as well as extract the diagonal elements of a matrix. More uses of the diag()
function can be explored by typing ?diag
in the R console window.
The code file provides a lot more functions that can used along with matrices—for example, functions related to finding a determinant or inverse of a matrix and matrix multiplication.
- 企業(yè)級Java EE架構(gòu)設(shè)計(jì)精深實(shí)踐
- Mastering OpenCV Android Application Programming
- Java完全自學(xué)教程
- PyTorch自動駕駛視覺感知算法實(shí)戰(zhàn)
- Building an RPG with Unity 2018
- Visual C#.NET程序設(shè)計(jì)
- Java EE 8 Application Development
- Nginx Lua開發(fā)實(shí)戰(zhàn)
- JavaScript腳本特效編程給力起飛
- Node學(xué)習(xí)指南(第2版)
- Python Linux系統(tǒng)管理與自動化運(yùn)維
- Mastering ArcGIS Server Development with JavaScript
- Clojure編程樂趣
- Mastering React Test:Driven Development
- Learning Predictive Analytics with R