0Pricing
R Academy · 课时

使用 matrix() 创建矩阵

通过指定 data、nrow、ncol 和 byrow 构建矩阵

使用 matrix() 创建矩阵 是 CoddyKit 上的免费 R Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。

R 中的矩阵是什么?

R 中的 matrix 是一种二维数据结构,其中所有元素都必须属于相同类型。您可以将它理解为由行和列组成的表格。矩阵是线性代数、图像处理和统计计算的重要工具。

# A simple 2x3 matrix
m <- matrix(1:6, nrow = 2, ncol = 3)
cat('A 2x3 matrix:
')
print(m)
cat('Dimensions:', dim(m), '
')  # rows cols

matrix(data, nrow, ncol)

matrix() 函数接收一个数据向量,并将其排列成行和列。默认情况下,R 按列填充矩阵(列主序)。

# Filled column by column (default)
m_col <- matrix(1:12, nrow = 3, ncol = 4)
cat('Column-filled 3x4 matrix:
')
print(m_col)
cat('Note: 1,2,3 fill the first COLUMN, not the first row
')

byrow = TRUE 按行填充

设置 byrow = TRUE 会按行填充矩阵。当您以行的形式思考数据(例如电子表格中的数据)时,这通常更直观。

# Filled row by row
m_row <- matrix(1:12, nrow = 3, ncol = 4, byrow = TRUE)
cat('Row-filled 3x4 matrix:
')
print(m_row)
cat('Note: 1,2,3,4 fill the first ROW
')

# Verify byrow
m_check <- matrix(c(1,2,3,4,5,6), nrow = 2, byrow = TRUE)
print(m_check)

从数据向量创建矩阵

您可以传入实际的数据向量来创建有意义的矩阵。如果向量短于 nrow * ncol,R 会循环使用该向量,但最佳实践是提供数量恰好正确的元素。

# Exam scores: 3 students, 4 subjects
scores_data <- c(88, 92, 75, 81,   # Student 1
                 79, 85, 90, 73,   # Student 2
                 95, 78, 82, 88)   # Student 3

exam_matrix <- matrix(scores_data, nrow = 3, ncol = 4, byrow = TRUE)
rownames(exam_matrix) <- c('Alice', 'Bob', 'Carol')
colnames(exam_matrix) <- c('Math', 'Science', 'English', 'History')
print(exam_matrix)

dim() — 检查维度

dim(m) 返回一个长度为 2 的数值向量:先是行数,然后是列数。您也可以使用 nrow(m) 和 ncol(m) 分别获取单个维度。

m <- matrix(1:20, nrow = 4, ncol = 5)
cat('dim(m):', dim(m), '
')       # 4 5
cat('nrow(m):', nrow(m), '
')     # 4
cat('ncol(m):', ncol(m), '
')     # 5
cat('Total elements:', length(m), '
')  # 20

is.matrix() — 检查类型

如果 x 是矩阵,is.matrix(x) 会返回 TRUE。这对于验证函数输入很有用。请注意,矩阵也是数组(is.array() 也会返回 TRUE)。

m <- matrix(1:4, nrow = 2)
v <- c(1, 2, 3, 4)

cat('is.matrix(m):', is.matrix(m), '
')  # TRUE
cat('is.matrix(v):', is.matrix(v), '
')  # FALSE
cat('is.array(m): ', is.array(m), '
')   # TRUE (matrix IS an array)
cat('class(m):    ', class(m), '
')

零矩阵和单位矩阵

您可以通过循环使用单个值来创建特殊矩阵。matrix(0, n, n) 创建零矩阵;diag(n) 创建 n x n 单位矩阵(对角线上为 1,其余位置为 0)。

# Zero matrix 3x3
zero_mat <- matrix(0, nrow = 3, ncol = 3)
cat('Zero matrix:
')
print(zero_mat)

# Identity matrix 3x3
identity_mat <- diag(3)
cat('Identity matrix:
')
print(identity_mat)

从循环使用的值创建矩阵

当数据向量短于 nrow * ncol 时,R 会循环使用该向量(从开头重新重复)。如果向量长度无法整除矩阵大小,R 会发出警告。

# Recycle a 2-element vector into a 4x4 matrix
alternate <- matrix(c(0, 1), nrow = 4, ncol = 4)
cat('Recycled 0,1 into 4x4:
')
print(alternate)

# Checkerboard effect: fills column by column

仅提供 nrow 或 ncol

您只需提供 nrow 或 ncol 其中一个,R 会根据数据长度自动计算另一个值。如果数据无法整除,R 会循环使用数据并发出警告。

# Only specify nrow, R infers ncol
m1 <- matrix(1:12, nrow = 3)
cat('nrow=3 only, inferred ncol =', ncol(m1), '
')
print(m1)

# Only specify ncol, R infers nrow
m2 <- matrix(1:12, ncol = 4)
cat('ncol=4 only, inferred nrow =', nrow(m2), '
')

字符矩阵

矩阵并不局限于数字——您可以创建字符矩阵,用于分类数据、游戏棋盘或查找网格。不过,所有元素仍必须属于相同类型。

# Tic-tac-toe board
board <- matrix(c('X', 'O', 'X',
                   'O', 'X', 'O',
                   'O', 'X', 'O'),
                nrow = 3, ncol = 3, byrow = TRUE)
cat('Tic-Tac-Toe board:
')
print(board)
cat('Type:', class(board), '
')

创建矩阵:总结

以下是在 R 中创建矩阵的方法总结:

  • matrix(data, nrow, ncol) — 基本创建方式(默认按列填充)
  • matrix(data, nrow, ncol, byrow=TRUE) — 按行填充
  • matrix(0, n, m) — 零矩阵
  • diag(n) — 单位矩阵
  • dim(m)、nrow(m)、ncol(m) — 查看维度
  • is.matrix(m) — 检查类型
# Quick creation reference
cat('3x2 column-fill:
'); print(matrix(1:6, 3, 2))
cat('3x2 row-fill:
');    print(matrix(1:6, 3, 2, byrow=TRUE))
cat('2x2 zeros:
');       print(matrix(0, 2, 2))
cat('3x3 identity:
');    print(diag(3))

快速检查

默认情况下(不使用 byrow = TRUE),matrix() 按什么顺序填充元素?

回顾:创建矩阵

做得很好!本课的要点如下:

  • matrix(data, nrow, ncol) 用于创建矩阵——默认按列填充数据
  • 使用 byrow = TRUE 可按行填充
  • 只需指定 nrow 或 ncol 中的一个——R 会推断另一个
  • dim(m) 返回 c(rows, cols);nrow() 和 ncol() 返回各自的数量
  • is.matrix() 用于测试对象是否为矩阵
  • matrix(0, n, n) 创建零矩阵;diag(n) 创建单位矩阵
# Full workflow: create, inspect, verify
m <- matrix(seq(2, 24, by = 2), nrow = 4, ncol = 3, byrow = TRUE)
cat('Even numbers matrix:
')
print(m)
cat('Rows:', nrow(m), '| Cols:', ncol(m), '| Elements:', length(m), '
')

常见问题解答

「使用 matrix() 创建矩阵」课时是免费的吗?

是的 — 「使用 matrix() 创建矩阵」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。

「使用 matrix() 创建矩阵」这节课中我会学到什么?

通过指定 data、nrow、ncol 和 byrow 构建矩阵 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 R Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 matrix() 创建矩阵」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 R Academy 课中编写并运行代码吗?

能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 matrix() 创建矩阵
  2. 矩阵索引与子集
  3. 矩阵算术与运算
  4. 矩阵转置与重塑
← 返回 R Academy