【问题标题】:Working with elements of a matrix as it was names of other matrices in R使用矩阵的元素,因为它是 R 中其他矩阵的名称
【发布时间】:2015-12-21 17:22:36
【问题描述】:

我有一个矩阵,其中保存了其他矩阵或向量的名称。

让我们这样说:

        col1   col2
row1    matA   matB
row2    matC   matD

其中 matA 和 matB =

matA:          col1        matB:           col1
       row1     119                row1     105
       row2      80                row2      99
       row3      95                row3      70

我将使用一个循环遍历第一个矩阵的所有行。

我需要计算 matA 和 matB 第一行的平均值并使用 matA = rbind(-calculated_average-,matA) 保存它,对于 matB 也是如此。所以结果应该是:

matA:          col1        matB:           col1
       row1     112                row1     112
       row2     119                row2     105
       row3      80                row3      99
       row4      95                row4      70

然后循环将移动到第二行并为 matC 和 matD 等计算相同的值。

如果不定义 matB,我需要创建它并将起始值设置为 101。结果将是:

matA:          col1        matB:           col1
       row1     110                row1     110
       row2     119                row2     101
       row3      80                
       row4      95                

我的问题的关键是一个函数,它允许我使用矩阵的元素,因为它是其他矩阵的名称。

【问题讨论】:

  • 当您说未定义矩阵时,您的意思是 R 中不存在变量 matB?还是矩阵为空?
  • R中不存在矩阵。

标签: r matrix


【解决方案1】:

欢迎来到 SO。

正如你自己提到的,问题的关键是一个函数,它允许使用它们的名称获取保存在内存中的对象。该函数的名称是get。您还需要考虑的另一个功能是ls() 检查内存中存储的变量是什么,assign 使用其名称作为字符串来分配变量。我假设如果未定义矩阵,则它不存在于内存中。

我写了一段可能解决你的问题的代码,它当然不是最优雅的解决方案,但它可以作为你的起点。

假设dt 是您的初始矩阵的名称。

for i in 1:nrow(dt){
  #check whether at least one matrix is defined
  if(dt[i,1] %in% ls() || dt[i,2] %in% ls()){
    #check whether first matrix is defined
    if(dt[i,1] %in% ls()){
      mat1 = get(dt[i,1])
    #if not define it
    }else{
      mat1 = matrix(101, c(1,1))
    }
    #do the same for the second matrix
    if(dt[i,2] %in% ls(){
      mat2 = get(dt[i,2])
    }else{
      mat2 = matrix(101, c(1,1))
    }
    #calculate averages and reassign
    assign(dt[i,1], rbind(mean(c(mat1[1,1],mat2[1,1])), mat1))
    assign(dt[i,2], rbind(mean(c(mat1[1,1],mat2[1,1])), mat2))
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多