代码之家  ›  专栏  ›  技术社区  ›  Jilber Urbina

`rowname`-ing矩阵列表

  •  5
  • Jilber Urbina  · 技术社区  · 12 年前

    假设我有一个矩阵列表,名为 Tables 带colname,不带rowname。

     Tables <- list(structure(c(0.810145949194718, 0.0792559803788517, 0.189854050805282, 
    0.920744019621148), .Dim = c(2L, 2L), .Dimnames = list(NULL, 
        c("e", "prod"))), structure(c(0.949326264941026, 0.24010922539329, 
    0.0506737350589744, 0.75989077460671), .Dim = c(2L, 2L), .Dimnames = list(
        NULL, c("prod", "e"))))
    

    我希望行名与列名相同:

    rownames(Tables[[1]])<- colnames(Tables[[1]])
    rownames(Tables[[2]])<- colnames(Tables[[2]])
    

    我试过使用 lapply 没有成功

    lapply(Tables, function(x) rownames(x) <- colnames(x))
    

    我用 for 环

    for(i in 1:length(Tables)){
      rownames(Tables[[i]])<- colnames(Tables[[i]])
    }
    
    Tables # Expected result
    [[1]]
                  e      prod
    e    0.81014595 0.1898541
    prod 0.07925598 0.9207440
    
    [[2]]
              prod          e
    prod 0.9493263 0.05067374
    e    0.2401092 0.75989077
    

    尽管如此,我还是想找到一种方法,使用任何 *apply 或base中的任何其他函数,以避免 对于 循环,但我不能在这个目标上成功。我读过 this 但我不知道如何使用这些解决方案。有什么建议吗?

    4 回复  |  直到 3 年前
        1
  •  7
  •   Henrik plannapus    12 年前
    lapply(Tables, function(x){
      rownames(x) <- colnames(x)
      x
    })
    
    # [[1]]
    #               e      prod
    # e    0.81014595 0.1898541
    # prod 0.07925598 0.9207440
    # 
    # [[2]]
    #           prod          e
    # prod 0.9493263 0.05067374
    # e    0.2401092 0.75989077
    
        2
  •  5
  •   Ricardo Saporta    12 年前

    另一种选择:

    for (x in Tables) 
       data.table::setattr(x, "dimnames", list(colnames(x), colnames(x))) 
    
    
    [[1]]
                  e      prod
    e    0.81014595 0.1898541
    prod 0.07925598 0.9207440
    
    [[2]]
              prod          e
    prod 0.9493263 0.05067374
    e    0.2401092 0.75989077
    
        3
  •  4
  •   flodel    12 年前

    R已经具备了您所需的一切:-)

    Tables <- Map(`rownames<-`, Tables, lapply(Tables, colnames))
    
        4
  •  1
  •   Adrian    12 年前

    有一种方法:

    lapply(seq_along(Tables), function(i) {
        rownames(Tables[[i]]) <<- colnames(Tables[[i]])
        return(invisible())
    })
    

    …这很难看——用一个循环代替。或者,如果你确实想使用lapply,可以尝试:

    Tables <- lapply(Tables, function(x) {
        rownames(x) <- colnames(x)
        return(x)
    })
    

    有人早些时候发布了这条消息,但他们似乎已经删除了自己的回答。