2.4.2 Array
Array is a data structure that can hold multiple values in a grid-like format, organized into dimensions (like rows, columns, and layers). Arrays can be one-dimensional (like a vector), two-dimensional (like a matrix), or multi-dimensional (with three or more dimensions).
Vector:
In R, a vector is one-dimensional array that contains data with same type. The outputs of the functions c
, seq
, and rep
are essentially vectors, with the only difference being that they are viewed as a sequence with a length, but do not have dimensional attributes. For example,
= seq(1,10, by = 0.1)
x class(x) # output is numeric
length(x) # output is 91
dim(x) # output is NULL
In some programming language, such kind of objects without dimensional attributes are called tuple. This means that we can slice this type of sequence object to extract the desired elements. We will introduce slicing in the discussion about vectors below.
One can use the array
function to embed the dimension attribute into such an object and then obtain a real vector, for example,
= seq(0,1,0.2)
x = array(x, dim = length(x))
x # length(x) is the default value for 'dim'
class(x)
length(x)
dim(x)
One can use [index]
to slice an array, for examples
# Guess the outputs first, verify them in R
= seq(0,1,by=0.2)
x 1] # the first element in an array
x[length(x)]
x[1:3]
x[c(1,2,5)]
x[rep(2:4, 3)]
x[-1]
x[-c(1,2,5)] x[
Some operations, examples
= seq(0,1,by=0.2)
x 2*x + 1 # elementwise operations
t(x) # transpose
dim(t(x)) # column vector
dim(t(t(x))) # row vector
Matrix:
Matrices in R are the same as matrices in linear algebra, that is matrix is a rectangle array. So, we can apply function array
to create matrix as well, but need to specify two numbers for the argument dim
. For example,
= array(1:10, dim = c(2,5))
X X
From the output of the example above we can see that we can only fill in the elements by columns. If we want to fill in the elements by rows, then we have to use another function matrix
. For example,
= matrix(1:10, nrow = 2, ncol = 5, byrow = FALSE)
X
X= matrix(1:10, nrow = 2, ncol = 5, byrow = TRUE)
X X
For slicing of matrix, see examples
# Guess the outputs first, verify them in R
= matrix(1:9,3,3,byrow=T)
X 1,2]
X[1,]
X[3]
X[,1:2,2:3]
X[array(c(1,2), dim = c(1,2)) ]
X[ array(c(1,2,3,2), dim = c(2,2)) ] X[
More operations for matrix, see examples
= matrix(1:9,3,3,byrow=T)
X *X # elementwise multiplication
X%*%X # matrix multiplication (in linear algebra)
Xt(X) # transpose
det(X) # calculate determinant
= matrix(c(1,2,2,1),2,2)
X eigen(X) # eigen decomposition of a square matrix
Two useful functions, cbind
and rbind
, which can combine objects by column and row, respectively. See examples,
= 1:3
x1 = 3:5
x2 X = cbind(x1,x2))
(X = rbind(x1,x2))
(class(X) # check the type of outputs