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

如何将矩阵列表转换为指定格式的DataFrame(R语言)

将矩阵列表转换为指定格式的DataFrame(R语言)

需求说明

已有通过R代码生成的矩阵列表Glist,需将其转换为包含三列的DataFrame:

  1. [run]:矩阵编号(对应原列表的索引)
  2. Actor-Receiver:矩阵的行-列编号(格式为行号-列号)
  3. Count:矩阵对应位置的数值(需保留所有0值)

解决方案

方法一:使用tidyverse工具链(推荐)

借助purrr和tibble包实现高效转换,代码如下:

library(tidyverse)

# 处理矩阵列表并生成目标DataFrame
result_df <- map_dfr(seq_along(Glist), function(run_num) {
  current_mat <- Glist[[run_num]]
  # 将矩阵转为长格式
  as.data.frame.table(current_mat, responseName = "Count") %>%
    mutate(
      Actor = as.numeric(Var1),
      Receiver = as.numeric(Var2),
      `[run]` = run_num,
      `Actor-Receiver` = str_c(Actor, "-", Receiver)
    ) %>%
    select(`[run]`, `Actor-Receiver`, Count)
})

代码解释

  • map_dfr:遍历矩阵列表,自动将每个矩阵的处理结果按行合并为单个DataFrame
  • as.data.frame.table:把矩阵转换为长格式,自动生成行号(Var1)、列号(Var2)和对应值(Count)
  • mutate:将行/列号转为数值类型,添加矩阵编号,拼接出Actor-Receiver格式的字符串
  • select:调整列顺序,只保留需要的三列

方法二:Base R实现

如果不想引入额外包,可使用基础R函数完成转换:

# 遍历矩阵列表生成单个数据框列表
temp_list <- lapply(seq_along(Glist), function(run_num) {
  current_mat <- Glist[[run_num]]
  # 生成所有行-列组合
  all_rows <- rep(1:nrow(current_mat), ncol(current_mat))
  all_cols <- rep(1:ncol(current_mat), each = nrow(current_mat))
  all_counts <- as.vector(current_mat)
  
  # 构建单run的数据框
  data.frame(
    `[run]` = run_num,
    `Actor-Receiver` = paste(all_rows, all_cols, sep = "-"),
    Count = all_counts,
    stringsAsFactors = FALSE
  )
})

# 合并所有数据框
result_df <- do.call(rbind, temp_list)

示例输出

转换后的DataFrame会包含所有矩阵的全部行-列组合(包括值为0的条目),部分示例如下:

[run] Actor-Receiver Count
    80         1-2     15
    80         1-3      9
    80         1-4      0
    ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:27:39