本文记录了:
- 创建矩阵;
- 转变矩阵元素的字符类型,e.g.字符型转变为数值型。
矩阵是一个二维数组,只是每个元素都拥有相同的模式(数值型、字符型或逻辑型)。
通过函数matrix()创建矩阵。在处理大型数据集时用矩阵,而不是数据框(矩阵更轻量级)
matrix()一般使用格式
myymatrix <- matrix(vector, nrow = number_of_rows, ncol = number_of_columns,
byrow = logical_value,
dimnames = list(char_vector_rownames, char_vector_colnames))
我的习惯:创建矩阵时就使用dimnames
设置行名和列名。
matrix()函数的默认设置(一般要注意下)
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,
dimnames = NULL)
1. 创建一个矩阵(元素为字符型)
默认按列来填充(byrow = FALSE
)
# elements of the matrix
cells <- c("1", "2", "3",
"4", "5", "6",
"7", "8", "9")
names_r <- c("R1", "R2", "R3") # row name
names_c <- c("C1", "C2", "C3") # column name
# Create a 3x3 matrix
my_matrix <- matrix(data = cells,
nrow = 3, ncol = 3,
byrow = TRUE, # matrix is filled by row.Fill by column by default (byrow=FALSE)
dimnames = list(names_r, names_c))
2. 将矩阵元素转变为数值型
my_matrix <- as.numeric(my_matrix)
我的代码:
https://github.com/wPencil/MyNotes/blob/7866d1982f584ad820e31c956fa03ff052fbe944/R/matrix.R