You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在矩阵上调用apply()为何遍历元素而非行?两行矩阵迭代咨询

Ah, I see where the confusion is coming from! The key here is understanding the MARGIN argument in apply()—it’s what controls whether you iterate over rows, columns, or individual elements of your matrix.

By default, apply() doesn’t guess what you want—you have to explicitly tell it which dimension to operate on with the MARGIN parameter:

  • Use MARGIN = 1 to iterate over rows: each iteration will pass an entire row (as a vector) to your function, which is exactly what you want.
  • Use MARGIN = 2 to iterate over columns: each iteration passes an entire column vector.
  • If you use MARGIN = c(1, 2) (or accidentally mis-specify the parameter), apply() will iterate over every single individual element in the matrix—this is why you’re getting single values instead of full rows.

Let’s walk through a concrete example with your two-column matrix:

# Create a sample 2-column matrix
enum <- matrix(c(1, 3, 2, 4), ncol = 2)
enum
#      [,1] [,2]
# [1,]    1    2
# [2,]    3    4

Wrong approach (gets individual elements):

If you run this, each y will be a single number:

apply(enum, c(1, 2), function(y) {
  cat("Current y:", y, "\n")
})
# Output:
# Current y: 1 
# Current y: 3 
# Current y: 2 
# Current y: 4 

Correct approach (gets full rows):

Use MARGIN = 1 to pass each row as a vector:

apply(enum, 1, function(y) {
  cat("Current y:", y, "\n")
})
# Output:
# Current y: 1 2 
# Current y: 3 4 

The reason your iterations were splitting into single elements instead of row vectors is almost certainly because you either specified MARGIN = c(1, 2) (which targets every element) or didn’t set MARGIN correctly. Just switch to MARGIN = 1, and you’ll get the full-row behavior you expected.

内容的提问来源于stack exchange,提问作者WestCoastProjects

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:41:03