Difference Between Vectors and Matrices
The
main differences between vectors and matrices in r programming:
Feature |
Vectors |
Matrices |
Dimensionality |
1D |
2D |
Syntax |
c(1, 2, 3) |
matrix(1:9, nrow=3) |
Element Access |
vec[1] |
mat[1, 2] |
Element Addition |
vec <- c(vec, 4) |
mat <- rbind(mat, c(10, 11, 12)) <br> mat <-
cbind(mat, c(4, 5, 6)) |
Element Deletion |
vec <- vec[-2] |
mat <- mat[-2, ] <br> mat <- mat[, -2] |
Concatenation |
c(vec1, vec2) |
rbind(mat1, mat2) <br> cbind(mat1, mat2) |
Mathematical Ops |
vec1 + vec2 |
mat1 + mat2 |
Element-wise Ops |
vec1 * vec2 |
mat1 * mat2 |
Transpose |
t(vec) |
t(mat) |
Special Functions |
sum(vec) |
apply(mat, 1, sum) |
Names |
vec <- c(a=1, b=2, c=3) |
colnames(mat) <- c("A", "B",
"C") <br> rownames(mat) <- c("X", "Y",
"Z") |
Ø Some additional points of difference are:
i.
Vectors can have any length,
whereas matrices have to have a specified number of rows and columns.
ii.
Vectors are 1-dimensional, whereas
matrices are 2-dimensional. This means that vectors have only one
"axis" or "dimension" to them, whereas matrices have two
(rows and columns).
iii.
Vectors are usually created using
the c() function, whereas matrices are created using the matrix() function
(although matrices can also be created using other functions like cbind() and
rbind()).
iv.
Accessing an element of a vector
requires only one index (e.g. vec[1]), whereas accessing an element of a matrix
requires two indices, one for the row and one for the column (e.g. mat[1, 2]).
v.
Vectors can be concatenated using
the c() function, whereas matrices can be concatenated using either rbind()
(for concatenating rows) or cbind() (for concatenating columns).
vi.
Mathematical operations on vectors
(e.g. vec1 + vec2) are performed element-wise, whereas mathematical operations
on matrices (e.g. mat1 + mat2) are performed element-wise on the corresponding elements.
vii.
Special functions like sum() can
be applied to vectors to compute a summary statistic, whereas for matrices, the
apply() function is typically used to apply a function to either rows or
columns (specified by the second argument).
viii.
Vectors can have named elements,
whereas matrices can have named rows and columns (specified using the
rownames() and colnames() functions).
No comments:
Post a Comment