--Managing Matrices
2-dimensional rectangular layout in R. Each element of matrix must be same data type such as numeric, character, etc.
#Creating Matrices
# numeric matrix
m1 <- matrix(1:6, nrow = 2, ncol = 3)
m1
## [,1] [,2] [,3]
## [1,] 1 3 5
## [2,] 2 4 6
str(m1)
## int [1:2, 1:3] 1 2 3 4 5 6
attributes(m1)
## $dim
## [1] 2 3
# a character matrix
m2 <- matrix(letters[1:6], nrow = 2, ncol = 3)
m2
## [,1] [,2] [,3]
## [1,] "a" "c" "e"
## [2,] "b" "d" "f"
# structure of m2 is simply character vector with 2x3 dimension
str(m2)
## chr [1:2, 1:3] "a" "b" "c" "d" "e" "f"
attributes(m2)
## $dim
## [1] 2 3
v1 <- 1:4
v2 <- 5:8
cbind(v1, v2)
## v1 v2
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
rbind(v1, v2)
## [,1] [,2] [,3] [,4]
## v1 1 2 3 4
## v2 5 6 7 8
# bind several vectors together
v3 <- 9:12
cbind(v1, v2, v3)
## v1 v2 v3
## [1,] 1 5 9
## [2,] 2 6 10
## [3,] 3 7 11
## [4,] 4 8 12#Adding on to Matrices
Use cbind() and rbind()functions for adding onto matrices as well.
#Adding Attributes to Matrices
#Subsetting Matrices
#Exercises
What are the attributes of the built-in
VADeathsdata matrix?Subset this matrix for only male death rates.
Subset for males death rates over the age of 60.
See if you can calculate averages for each column and row.
Can you figure out how to add these averages to your table so the output looks like:
Last updated