【问题标题】:Passing as a variable the individual columns of individual matrices in a list of matrices将矩阵列表中各个矩阵的各个列作为变量传递
【发布时间】:2014-11-12 20:01:39
【问题描述】:

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

【问题讨论】:

    标签: arrays r list for-loop matrix


    【解决方案1】:

    你可以使用数字索引吗?例如,矩阵 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
    

    【讨论】:

    • 喂!谢谢你。简单的回答。我一定已经尝试了所有其他可能的语法组合,并且不断收到不正确数量的暗淡错误;在 3 个文本或网络上的许多搜索中找不到这个答案。谢谢!
    • 乐于助人!列表索引有点奇怪。 my_list[1] 是长度为 1 的列表。my_list[[1]] 是列表位置 1 中的任何内容。
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2015-11-03
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2014-05-15
    相关资源
    最近更新 更多