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

R语言循环操作矩阵时报下标数量错误的原因及解决方法

第一个报错(incorrect number of subscripts on matrix)原因与解决

原因

核心问题是循环内直接覆盖了原始概率矩阵变量:

  • 第一次循环执行prob_matrix = solution_matrix(prob_matrix, t)后,原始的概率值矩阵被替换为包含NA、行号的处理后矩阵
  • 第二次及之后的循环,传入solution_matrix的已经不是原始概率矩阵,无法正常计算混淆矩阵指标,导致compare_true_est_sol返回的结果结构异常,不是长度匹配的命名向量,赋值给rates[2,i]时触发下标错误

解决方法

修改循环内变量名,保留原始概率矩阵不被覆盖:

thresholds <- c(1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2,1e-1,1)
rates = matrix(0,2,length(thresholds))
# 提前保存原始概率矩阵
original_prob <- prob_matrix
for (i in 1:length(thresholds)) {
  t = thresholds[i]
  # 用新变量存储处理后的矩阵,不修改原始数据
  processed_matrix = solution_matrix(original_prob, t)
  compare_true_est_sol = compare_solutions(synthetic_solution, processed_matrix)
  rates[1,i] = compare_true_est_sol["TP"]/(compare_true_est_sol["TP"]+compare_true_est_sol["FN"]) 
  rates[2,i] = compare_true_est_sol["FP"]/(compare_true_est_sol["FP"]+compare_true_est_sol["TN"])
}
return(rates)

第二个报错(missing value where TRUE/FALSE needed)原因与解决

原因

两个触发场景:

  1. 上述变量覆盖问题未解决,传入solution_matrix的矩阵已经携带NA,probability_matrix>=threshold运算会返回NA,if (NA == TRUE)没有合法布尔值触发报错
  2. 原始概率矩阵本身存在NA值,阈值判断时生成NA导致判断异常

解决方法

修改solution_matrix函数,增加NA值处理逻辑:

solution_matrix <- function(probability_matrix, threshold){
  # 阈值判断,同时把NA统一转为FALSE
  probability_matrix = probability_matrix >= threshold
  probability_matrix[is.na(probability_matrix)] = FALSE
  
  solution_matrix = probability_matrix
  for (i in 1:nrow(solution_matrix)){
    for (j in 1:ncol(solution_matrix)){
      if (solution_matrix[i,j] == TRUE){
        solution_matrix[i,j]  = i-1
      } else {
        solution_matrix[i,j]  = NA
      }
    }
  }
  for (j in 1:ncol(solution_matrix)){
    solution_matrix[,j] = sort(as.numeric(solution_matrix[,j]), na.last = TRUE) 
  }
  
  colnames(solution_matrix) <- gsub("\\.", "-", colnames(solution_matrix))  
  return(solution_matrix)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:00:00