2015-12-21 90 views
1

我有一个矩阵,其中保存了其他矩阵或向量的名称。使用矩阵的元素,因为它是R中其他矩阵的名称

比方说,像这样:

 col1 col2 
row1 matA matB 
row2 matC matD 

凡马塔和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 

然后周期将进入第2行计算相同的MATC和matD等

如果MATB不会定义,我需要去创造和启动值设置为101,结果则是:

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

的关键,我的问题是一个函数,它可以让我用矩阵的元素,因为它是其他矩阵名工作。

+0

当你说矩阵没有定义时,你的意思是变量matB不存在于R中?或者矩阵是空的? – user974514

+0

矩阵不存在于R. –

回答

0

欢迎来到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)) 
    } 
}