将矩阵列表中各个矩阵的各列作为变量传递

时间:2014-11-12 20:01:39

标签: arrays r list for-loop matrix

我想将各种矩阵中的列传递给for循环。

如果我的两个矩阵的列数相同,我可能会这样做:

mat1 = matrix(rep(1:25), 5,5)
mat2 = matrix(rep(26:50), 5,5)
array.mat = array(c(mat1,mat2), dim=c(5,5,2))
mat1.ncol = ncol(mat1)
mat2.ncol = ncol(mat2)
mat.ncol = c(mat1.ncol, mat2.ncol)
mat.ncol
array.mat
for (dimi in 1:2){
  dim.col = mat.ncol[dimi]
    for (coli in 1:dim.col){
      st = shapiro.test(array.mat[,coli,dimi])$p.value
        if(st > .001){
          array.mat[,coli,dimi] = log(array.mat[,coli,dimi])
}}}

但是,我的数据列数不同,所以我想改用矩阵列表。

mat1 = matrix(rep(1:10), 5,2)
mat2 = matrix(rep(26:50), 5,5)
list.mat=list(a=mat1, b=mat2)
list.mat

但我无法弄清楚我是如何通过矩阵的列的?

list.mat$a[1:5] 

给出第一个矩阵的第一列,但是如何在循环中传递$ a和[startindex:endindex]?我看到的所有其他答案都倾向于传递两个矩阵的第i个元素(例如,列)。我需要将两个矩阵(a和b)分开以供以后的计算,但我希望它们(这两个矩阵的列表)一起用于这些类型的循环。 再一次,我可能只是错误地思考这个问题。谢谢你的任何想法。

1 个答案:

答案 0 :(得分:0)

你能用数字索引吗?例如,矩阵1,第1列:list.mat[[1]][,1]

循环:

for (m in 1:2) {
  for (i in 1:ncol(list.mat[[m]])) {
    cat('Here is matrix', m, ', columnn', i, '\n')
    print(list.mat[[m]][,i])
  }
}

结果:

Here is matrix 1 , columnn 1 
[1] 1 2 3 4 5
Here is matrix 1 , columnn 2 
[1]  6  7  8  9 10
Here is matrix 2 , columnn 1 
[1] 26 27 28 29 30
Here is matrix 2 , columnn 2 
[1] 31 32 33 34 35
Here is matrix 2 , columnn 3 
[1] 36 37 38 39 40
Here is matrix 2 , columnn 4 
[1] 41 42 43 44 45
Here is matrix 2 , columnn 5 
[1] 46 47 48 49 50