【问题标题】:Removing rows in R based on values in a single column根据单列中的值删除 R 中的行
【发布时间】:2012-05-02 09:12:35
【问题描述】:

我在 R 中有一个 n x 3 矩阵,想要删除最后一列小于 x 的所有行。最好的方法是什么?

【问题讨论】:

    标签: r


    【解决方案1】:

    您也可以使用subset() 函数。

    a <- matrix(1:9, nrow=3)  
    threshhold <- 8  
    subset(a, a[ , 3] < threshhold)  
    

    【讨论】:

      【解决方案2】:

      与@JeffAllen 方法相同,但更详细一点,并且可以推广到任何大小的矩阵。

          data <- rbind(c(1,2,3), c(1, 7, 4), c(4,6,7), c(3, 3, 3), c(4, 8, 6))
          data
               [,1] [,2] [,3]
          [1,]    1    2    3
          [2,]    1    7    4
          [3,]    4    6    7
          [4,]    3    3    3
          [5,]    4    8    6
          #
          # set value of x
          x <- 3
          # 
          # return matrix that contains only those rows where value in 
          # the final column is greater than x. 
          # This will scale up to a matrix of any size 
          data[data[,ncol(data)]>x,]
               [,1] [,2] [,3]
          [1,]    1    7    4
          [2,]    4    6    7
          [3,]    4    8    6
      

      【讨论】:

        【解决方案3】:
        m <- matrix(rnorm(9), ncol=3)
        m <- m[m[,3]>0,]
        

        创建一个矩阵,然后重新定义该矩阵以仅包含第三列大于 0 的行 (m[,3] &gt; 0)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-21
          • 2021-08-09
          • 1970-01-01
          • 1970-01-01
          • 2019-07-06
          • 1970-01-01
          • 2021-05-13
          • 2016-07-27
          相关资源
          最近更新 更多