Create and Name Matrices
Create and Name Matrices
Introduction to R
Matrix
Introduction to R
Create a matrix
matrix()
Introduction to R
Introduction to R
rbind(), cbind()
> cbind(1:3, 1:3)
[,1] [,2]
[1,]
1
1
[2,]
2
2
[3,]
3
3
> rbind(1:3, 1:3)
[,1] [,2] [,3]
[1,]
1
2
3
[2,]
1
2
3
Introduction to R
rbind(), cbind()
> m <- matrix(1:6, byrow = TRUE, nrow = 2)
> rbind(m, 7:9)
[,1] [,2] [,3]
[1,]
1
2
3
[2,]
4
5
6
[3,]
7
8
9
> cbind(m, c(10, 11))
[,1] [,2] [,3] [,4]
[1,]
1
2
3
10
[2,]
4
5
6
11
Introduction to R
Introduction to R
Naming a matrix
> m <- matrix(1:6, byrow = TRUE, nrow = 2)
Introduction to R
Naming a matrix
> m <- matrix(1:6, byrow = TRUE, nrow = 2,
dimnames = list(c("row1", "row2"),
c("col1", "col2", "col3")))
> m
Introduction to R
Coercion
> num <- matrix(1:8, ncol = 2)
> num
[,1] [,2]
[1,]
1
5
[2,]
2
6
[3,]
3
7
[4,]
4
8
> char <- matrix(LETTERS[1:6], nrow = 4, ncol = 3)
> char
[,1] [,2] [,3]
[1,] "A" "E" "C"
[2,] "B" "F" "D"
[3,] "C" "A" "E"
[4,] "D" "B" "F"
Introduction to R
Coercion
> num <- matrix(1:8, ncol = 2)
> char <- matrix(LETTERS[1:6], nrow = 4, ncol = 3)
> cbind(num, char)
[,1] [,2] [,3]
[1,] "1" "5" "A"
[2,] "2" "6" "B"
[3,] "3" "7" "C"
[4,] "4" "8" "D"
[,4]
"E"
"F"
"A"
"B"
[,5]
"C"
"D"
"E"
"F"
INTRODUCTION TO R
Lets practice!