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

在R语言中用循环实现基于数据框的矩阵计数与求和填充

解决方案

首先先确认你的数据和初始矩阵的规范定义(修正了矩阵赋值的换行问题,保证代码可直接运行):

# 定义数据框
df <- data.frame(
  names1 = c('dog','dog','mouse','cat','dog','cat','cat','dog','mouse','mouse'),
  names2 = c('cat','dog','cat','cat','cat','dog','dog','dog','mouse','cat'),
  values = c(11,5,41,25,101,78,12,41,6,77)
)

# 定义初始全0矩阵
row_names <- unique(df$names1)
col_names <- unique(df$names2)
# 计数矩阵初始结构
count_matrix <- matrix(0, nrow = length(row_names), ncol = length(col_names))
rownames(count_matrix) <- row_names
colnames(count_matrix) <- col_names
# 求和矩阵初始结构(复用计数矩阵的行列结构)
sum_matrix <- count_matrix

1. 填充计数矩阵(统计交集数量)

通过嵌套循环遍历矩阵的每一行和每一列,匹配df中names1对应行名、names2对应列名的记录总数:

# 获取矩阵的行名和列名列表
rows <- rownames(count_matrix)
cols <- colnames(count_matrix)

# 嵌套循环填充计数矩阵
for (i in seq_along(rows)) {
  current_row <- rows[i]
  for (j in seq_along(cols)) {
    current_col <- cols[j]
    # 统计满足条件的记录行数
    count_matrix[i, j] <- sum(df$names1 == current_row & df$names2 == current_col)
  }
}

# 查看最终计数矩阵
count_matrix

运行结果:

dog mouse cat
dog    2     0   3
mouse  0     1   2
cat    2     0   1

2. 填充求和矩阵(统计对应values之和)

逻辑和计数矩阵一致,仅将统计行数改为对values列求和:

# 嵌套循环填充求和矩阵
for (i in seq_along(rows)) {
  current_row <- rows[i]
  for (j in seq_along(cols)) {
    current_col <- cols[j]
    # 对满足条件的values值求和
    sum_matrix[i, j] <- sum(df$values[df$names1 == current_row & df$names2 == current_col])
  }
}

# 查看最终求和矩阵
sum_matrix

运行结果:

dog mouse cat
dog    46     0 113
mouse   0     6 118
cat    90     0  25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:05:19