官术网_书友最值得收藏!

Matrices

A matrix is a 2D vector with rows and columns. In R, one requirement for matrices is that every data element stored inside it be of the same type (all character, all numeric, and so on). This allows you to perform arithmetic operations with matrices, if, for example, you have two that are both numeric.

Let's use matrix() to create a matrix, examine its class, use rownames() and colnames() to set row and column names, and access different elements of the matrix using multiple methods. Follow the steps given below:

  1. Use matrix() to create matrix1, a 3 x 3 matrix containing the numbers 1:12 by column, using the following code:
matrix1 <- matrix(c(1:12), nrow = 3, ncol = 3, byrow = FALSE)
  1. Create matrix2 similarly, also 3 x 3, and fill it with 1:12 by row, using the following code:
matrix2 <- matrix(c(1:12), nrow = 3, ncol = 3, byrow = TRUE) 
  1. Set the row and column names of matrix1 with the following:
rownames(matrix1) <- c("one", "two", "three") 
colnames(matrix1) <- c("one", "two", "three")
  1. Find the elements at the following positions in matrix1 using matrix indexing:
matrix1[1, 2]
matrix1["one",]
matrix1[,"one"]
matrix1["one","one"]

The output of the code is as follows:

主站蜘蛛池模板: 迁安市| 离岛区| 晋宁县| 堆龙德庆县| 吴堡县| 枣阳市| 台安县| 临朐县| 昆山市| 聂拉木县| 田东县| 阳曲县| 清镇市| 满城县| 志丹县| 五河县| 大田县| 龙岩市| 卓资县| 建宁县| 涞水县| 舞钢市| 扬州市| 阳新县| 蒲城县| 鄂托克前旗| 华蓥市| 昆明市| 叙永县| 高邑县| 登封市| 宝应县| 东平县| 精河县| 西乡县| 西贡区| 瑞安市| 比如县| 乌海市| 桃园县| 乡城县|