【问题标题】:How do I move particular rows to the end of my matrix in R?如何将特定行移动到 R 中矩阵的末尾?
【发布时间】:2017-10-13 05:51:53
【问题描述】:

我有一个包含一些空行和空列的矩阵。我想将空行和空列一直移动到矩阵右侧和底部的末尾。

我已经设法获得了所有空行的行名和列名。

我想做什么:

  1. 创建一个for循环,根据索引删除所有行和列(这不起作用,因为每次删除后空行的顺序都会改变,所以我放弃了这个想法)
  2. 根据行名的属性删除行。

Cnew = Cnew[!(Cnew$rownames %in% empty_rownames)]

似乎无法让它工作......

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    假设您有一个 6x6 矩阵,其中包含一列和一空行(意味着它们的所有条目都是 NA

    Cnew <- matrix(nrow = 6, ncol = 6, data = 1)
    
    Cnew[,4] <- NA
    Cnew[3,] <- NA
    
    empty.columns <- which(colSums(Cnew, na.rm = TRUE) == 0)
    empty.rows <- which(rowSums(Cnew, na.rm = TRUE) == 0)
    
    # we first delete the row and cols
    
    # for deleting do
    Cdel <- Cnew[-empty.rows,-empty.columns]
    
    # and then paste the rows and cols at the edges again
    Cdel <- cbind(Cdel, rep(NA, length(empty.columns)))
    Cdel <- rbind(Cdel, rep(NA, length(empty.rows)))
    

    【讨论】:

      【解决方案2】:

      如果仅用于删除某些列中具有 NA 值的行(观察)

      test <-matrix( 
           c(rep(c(NA, 1:9), 8)  ), 
           nrow=10, 
           ncol=8) 
      test <- test[complete.cases(test),]
      

      【讨论】:

        猜你喜欢
        • 2017-08-18
        • 2015-09-05
        • 1970-01-01
        • 2017-07-17
        • 2021-09-11
        • 2014-05-19
        • 1970-01-01
        • 1970-01-01
        • 2021-01-03
        相关资源
        最近更新 更多