【问题标题】:Incorrect number of subscripts on a large matrix from loop循环中大矩阵上的下标数量不正确
【发布时间】:2021-11-07 15:32:14
【问题描述】:

我有一个名为 rates 的简单矩阵代码,效果很好。

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))
for (i in 1:length(thresholds)) {
    rates[1,i] = 1 
    rates[2,i] = 1

但是,当我将相同的想法应用于更大的数据(矩阵)时,不知何故会出现错误。

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))
   for (i in 1:length(thresholds)) {
   t = thresholds[i]
   prob_matrix = solution_matrix(prob_matrix, t)
   compare_true_est_sol = compare_solutions(synthetic_solution, prob_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)

我附上照片 以查看矩阵示例。 solution_matrix() 和 compare_solutions() 是您可以忽略的函数。错误是“

速率错误[2, i]

"。请任何人帮助为什么会发生错误以及如何解决它?

更新:我遵循@BrianMontgomery 的建议,它适用于 thresholds = c(1) is a vector with one element,但是当我将 thresholds 设置为具有多个元素的向量时发生错误,例如 thresholds = c(1, 2)。错误是“if (solution_matrix[i, j] == TRUE) { 中的错误: 需要 TRUE/FALSE 的缺失值”。solution_matrix 的代码如下。

solution_matrix <- function(probability_matrix, threshold){
   probability_matrix = probability_matrix>=threshold

   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) 
 }

solution_matrix = solution_matrix
colnames(solution_matrix) <- gsub("\\.", "-", 
colnames(solution_matrix))  

return(solution_matrix)
}

【问题讨论】:

  • 我认为我们不能忽略这些函数,因为我在您提供的代码中看不到“结果”对象。哪一行给出了错误?我建议在这些函数上使用 debugonce()。
  • 如果没有您要求我们忽略的功能,则无法复制错误。
  • 我们需要能够在我们自己的系统上重现错误。除了你,没有人可以运行它。

标签: r matrix vector


【解决方案1】:

您将 compare_true_est_sol 视为一个向量,但它是一个行名为“1”的 1 x 4 矩阵。
所以要么使用compare_true_est_sol[1, "FP"],要么将其设为向量:

compare_true_est_sol <- unlist(compare_true_est_sol[1, ])

【讨论】:

  • 我已经按照您的建议进行了更改。当我的阈值 = c(1) 是单个向量时,它可以工作,但是当我尝试设置阈值时。 = c(1, 2) 发生错误。错误是“if (solution_matrix[i, j] == TRUE) { 中的错误:需要 TRUE/FALSE 的缺失值”。我对此一无所知。我试图在这里包含 solution_matrix 函数,但我不能
  • 错误出现在哪一行?此时您可能希望从一个可重现的示例重新开始。我跟不上这个。
  • 阈值的第二个元素调用solution_matrix函数时出错。我将尝试做一个可简化的示例,但这很困难,因为调用该函数需要一些必需的函数。
【解决方案2】:

我已经解决了这个问题。我试图制作一个可重现的例子,但这比我预期的要困难。我通过将变量“prob_matrix”重命名为“sol”来解决它。发生错误是因为变量名“prob_matrix”与 solution_matrix(prob_matrix, t) 的参数名相似,因此 for 循环在第二次迭代中不起作用。

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 1970-01-01
    • 2021-01-05
    • 2017-02-20
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多