3. Working with Matrices Flashcards
Naming matrix rows and columns
Assign name attributes to rows of a matrix:
rownames(matrix)
Assign name attributes to columns of a matrix:
colnames(matrix)
Matrix operations
Finding Matrix Dimensions
- dim(math_chemistry)
Combining Vectors or Matrices by Row
- rbind(matrix_1, matrix_2)
- rbind(vector_1, vector_2)
- rbind(vector_1, matrix_1)
Combining Vectors or Matrices by Column
- cbind(matrix_1, matrix_2)
- cbind(vector_1, vector_2)
- cbind(vector_1, matrix_1)
Indexing matrices by element
Extract a single element:
- matrix[2,5]
- matrix[“Stanford”,”patents”]
Extract multiple elements:
- matrix[c(1,2),c(1,3)]
- matrix[c(“Harvard”,”Stanford”),c(“world_rank”,”influence”)]
Indexing matrices by rows and columns
Extract a single row:
- matrix[1,]
- matrix[“Harvard”,]
Extract a single column:
- matrix[,2]
- matrix[,”quality_of_education”]
Extract multiple rows or columns:
- matrix[,c(“quality_of_education”,”influence”,”broad_impact”)]
- matrix[,c(“2,3,4”)]
Rank values of a vector
Rank values of a vector:
- rank(vector)
Rank values of a matrix:
- rank(matrix[,”column”])
- rank(matrix[“row”,])
Calculate the sum of values in a vector or a matrix
Sum of values in a vector:
- sum(vector)
Sum of values in a matrix:
- sum(matrix[,”column”])
- sum(matrix[“row”,])
Concepts
Like vectors, matrices only contain one data type. Unlike vectors, they are two-dimensional.
When adding a vector to a matrix, it’s good practice to make sure the new vector is the same length as the number of rows or columns in the matrix.