Lecture 4_activity 7 Below is the vector nature of matrices.
z <- matrix(1:8,nrow=4)
z
## [,1] [,2]
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
length(z)#As z is still a vector, we can query its length
## [1] 8
class(z)
## [1] "matrix" "array"
dim(z)
## [1] 4 2
Avoiding Unintended Dimension Reduction
Four-row matrix.
z
## [,1] [,2]
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
We extracted a row.
r <- z[2,]
r
## [1] 2 6
These are the ways to confirm that r is a vector of length 2, rather than a 1-by-2 matrix.
attributes(z)
## $dim
## [1] 4 2
attributes(r)
## NULL
str(z)
## int [1:4, 1:2] 1 2 3 4 5 6 7 8
str(r)
## int [1:2] 2 6
The drop argument using matrix z.
r <- z[2,, drop=FALSE]
r
## [,1] [,2]
## [1,] 2 6
dim(r)
## [1] 1 2
class(r)
## [1] "matrix" "array"
Naming Matrix Rows and Columns
z
## [,1] [,2]
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
Adding names to the entities.
colnames(z)
## NULL
colnames(z) <- c("a","b")
z
## a b
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
colnames(z)
## [1] "a" "b"
z[,"a"]
## [1] 1 2 3 4
Higher-Dimensional Arrays
firsttest <- matrix(nrow=3,ncol=2)
firsttest[1,1] <- 46
firsttest[2,1] <- 21
firsttest[1,2] <- 30
firsttest[2,2] <- 25
firsttest[3,1] <- 50
firsttest[3,2] <- 50
firsttest
## [,1] [,2]
## [1,] 46 30
## [2,] 21 25
## [3,] 50 50
secondtest <- matrix(nrow=3,ncol=2)
secondtest[1,1] <- 46
secondtest[2,1] <- 41
secondtest[1,2] <- 43
secondtest[2,2] <- 35
secondtest[3,1] <- 50
secondtest[3,2] <- 50
secondtest
## [,1] [,2]
## [1,] 46 43
## [2,] 41 35
## [3,] 50 50
tests <- array(data=c(firsttest,secondtest),dim=c(3,2,2))
attributes(tests)
## $dim
## [1] 3 2 2
tests[3,2,1]
## [1] 50
tests
## , , 1
##
## [,1] [,2]
## [1,] 46 30
## [2,] 21 25
## [3,] 50 50
##
## , , 2
##
## [,1] [,2]
## [1,] 46 43
## [2,] 41 35
## [3,] 50 50