代码之家  ›  专栏  ›  技术社区  ›  Kumpelka

R-所有列中条件下数据帧的子集行

  •  0
  • Kumpelka  · 技术社区  · 8 年前

    我希望将数据帧的行子集为所有列中的单个条件,避免使用 subset .

    我知道如何对单个列进行子集,但我不能对所有列进行泛化(不调用所有列)。

    初始数据帧:

      V1 V2 V3
    1  1  8 15
    2  2  0 16
    3  3 10 17
    4  4 11 18
    5  5  0 19
    6  0 13 20
    7  7 14 21
    

    在本例中,我想将不带零的行子集。

    预期产出:

      V1 V2 V3
    1  1  8 15
    2  3 10 17
    3  4 11 18
    4  7 14 21
    

    谢谢

    2 回复  |  直到 8 年前
        1
  •  1
  •   ira    8 年前
    # create your data
    a <- c(1,2,3,4,5,0,7)
    b <- c(8,0,10,11,0,14,14)
    c <- c(15,16,17,18,19,20,21)
    data <- cbind(a, b, c)
    
    # filter out rows where there is at least one 0
    data[apply(data, 1, min) > 0,]
    
        2
  •  0
  •   Prradep    8 年前

    使用 rowSums 匹配后的函数 0 .

    # creating your data
    data <- data.frame(a = c(1,2,3,4,5,0,7), 
                       b = c(8,0,10,11,0,14,14), 
                       c = c(15,16,17,18,19,20,21))
    
    # Selecting rows containing no 0.
    data[which(rowSums(as.matrix(data)==0) == 0),]
    

    另一种方式

    data[-unique(row(data)[grep("^0$", unlist(data))]),]