![]() |
VOOZH | about |
In R, vectors can be integer, double, character, logical, complex and raw types. A vector is created using the c() function:
a <- c(val1, val2, ...
A list of vectors in R is an array of more than one vector kept in a list structure. Creating a list of vectors is done in the following way:
[1] "The list of vectors is: " [[1]] [1] 1 2 3 4 [[2]] [1] 2 3 4 5 [[3]] [1] 3 4 5 6 [[4]] [1] 4 5 6 7 [[5]] [1] 5 6 7 8
Matrices in R can be formed from a list of vectors with the help of functions such as do.call() and matrix().
do.call() helps you execute a function (such as rbind()) on a list of arguments. Here's how to use it to form a matrix:
Output:
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 2 3 4 5
[3,] 3 4 5 6
[4,] 4 5 6 7
[5,] 5 6 7 8
we call the do.call() function and pass the arguments as rbind and a.
The matrix() function is used to transform a list of vectors into a matrix. To accomplish this, we first transform the list into a single vector with unlist(), then form the matrix:
Syntax:
matrix(data, nrow, ncol, byrow, dimnames)
Where,
[,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 2 3 4 5 6 [3,] 3 4 5 6 7 [4,] 4 5 6 7 8 [5,] 5 6 7 8 9 [6,] 6 7 8 ...