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

使用R的robustrao包构建学科相似性矩阵遇格式问题求助

解决robustrao包所需矩阵格式问题

问题背景

我正在开展大学项目,需测量一组科研论文的跨学科性,计划使用R语言的robustrao包。使用该包需构建学科相似性矩阵及论文-被引学科数据框,但构建矩阵时,即便使用了as.matrix函数,生成的结果仍被识别为数据表而非目标的Large Matrix格式。我无R语言使用经验,附上相关代码,期望得到类似pubdata1.RData的矩阵格式,请求协助解决。

原代码:

donnees <- read.csv("data1.csv", sep = ";", header = FALSE)
if (dim(donnees)[1] != 254 | dim(donnees)[2] != 254) {
  stop("Les dimensions des données ne correspondent pas à 254 x 254.")
}
noms_colonnes <- readLines("nom_colonnes.txt")
noms_lignes <- noms_colonnes
matrice <- matrix(numeric(), nrow = 254, ncol = 254)
colnames(matrice) <- noms_colonnes
rownames(matrice) <- noms_lignes
matrice <- as.matrix(donnees)
colnames(matrice) <- noms_colonnes
rownames(matrice) <- noms_lignes
print(rownames(matrice))

解决方案

问题核心在于数据读取类型错误、冗余步骤干扰,以及未匹配robustrao要求的矩阵类型。以下是修正后的代码:

# 读取数据时强制按原始格式读取,避免自动转因子
donnees <- read.csv("data1.csv", sep = ";", header = FALSE, stringsAsFactors = FALSE)

# 检查矩阵维度
if (dim(donnees)[1] != 254 | dim(donnees)[2] != 254) {
  stop("数据维度不符合254×254要求。")
}

# 读取行列名并检查数量匹配
noms_colonnes <- readLines("nom_colonnes.txt")
if (length(noms_colonnes) != 254) {
  stop("行列名数量与矩阵维度不匹配。")
}

# 将数据框转换为数值矩阵(强制确保数值类型)
matrice <- as.matrix(donnees)
matrice <- apply(matrice, 2, as.numeric)

# 设置行列名
colnames(matrice) <- noms_colonnes
rownames(matrice) <- noms_colonnes

# 检查当前矩阵类型
print(class(matrice))

# 若需转换为robustrao兼容的Large Matrix(Matrix包对象):
# 先安装Matrix包(首次运行时执行)
# install.packages("Matrix")
library(Matrix)
matrice_large <- as(matrice, "Matrix")
print(class(matrice_large))

# 保存为类似pubdata1.RData的格式
save(matrice_large, file = "mymatrix.RData")

关键说明

  1. 读取数据时添加stringsAsFactors=FALSE,防止csv中的数值被误转为因子类型;
  2. 增加行列名数量校验,避免维度不匹配问题;
  3. 通过apply强制将矩阵转为数值型,确保符合学科相似性矩阵的数值要求;
  4. 若robustrao要求使用Matrix包的Large Matrix对象,通过as(matrice, "Matrix")完成转换;
  5. 去掉冗余的空矩阵创建步骤,直接基于读取的数据生成目标矩阵。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:18:14