In this section we discuss matrices and vectors, and then we discuss how we can create a matrix and a vector in the R programming environment.

EXAMPLE 1: In R, we can use c() function to create a vector. For example,

V <- c(907,220,625,502)

The notation of <- is equivalent to an = sign. We are assigning v as the 4-dimensional vector above. When you type v in R, then you will see

V
## [1] 907 220 625 502

EXAMPLE 2: In R, using “:” you can easily create a vector of a sequence of numbers. In this example, you can type

V <- 2:6

to create the vector. If you type v in R it returns:

V
## [1] 2 3 4 5 6

EXAMPLE 3: In R we can create this matrix by calling the matrix() function.

M <- matrix(c(1,1,1,2,1,3,1,4),nrow=2,ncol=4)

If you type M in R, then you will see the output as follows:

 M
##      [,1] [,2] [,3] [,4]
## [1,]    1    1    1    1
## [2,]    1    2    3    4

Now suppose we want to have just the first column vector of this matrix M, then we type:

M[1,]
## [1] 1 1 1 1

Similarly, if we want to have the second column of the matrix M, then we type

M[,2]
## [1] 1 2

Let us define r1 and r2 as the first row vector and the second row vector of the matrix. In R we can define as

r1 <- c(1, 1, 1, 1)
r2 <- c(1, 2, 3, 4)

Then we use the rbind() function to create a matrix M as

M <- rbind(r1, r2)

If you type M in R, then the output looks

M
##    [,1] [,2] [,3] [,4]
## r1    1    1    1    1
## r2    1    2    3    4

To create a matrix from column vectors in R we can use the function cbind(). For this example we first create four column vectors c1, c2, c3, and c4 with a function c()

c1 <- c(1, 1)
c2 <- c(1, 2)
c3 <- c(1, 3)
c4 <- c(1, 4)

Then you use the cbind() function to create a matrix as follows:

M <- cbind(c1,c2,c3,c4)

If you type M, then you can see how M looks in R:

M
##      c1 c2 c3 c4
## [1,]  1  1  1  1
## [2,]  1  2  3  4

EXAMPLE 4: In R you can create the 5-dimensional zero vector using the rep() function.

rep(0, 5)
## [1] 0 0 0 0 0

If you want to create a 10-dimensional vector with all 1s as its elements then you type rep(1, 10). Then the output in R looks like this:

rep(1, 10)
##  [1] 1 1 1 1 1 1 1 1 1 1

EXAMPLE 5: We create here the identity matrix of size 3 and the identity matrix of size 4 in R with the diag() function. If you type

diag(3)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    1    0
## [3,]    0    0    1

Similarly, if you type diag(4), then you will see the following output in R:

diag(4)
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    0    0
## [2,]    0    1    0    0
## [3,]    0    0    1    0
## [4,]    0    0    0    1