How to remove rows with any zero value

前端 未结 8 680
时光取名叫无心
时光取名叫无心 2020-11-28 07:04

I have a problem to solve how to remove rows with a Zero value in R. In others hand, I can use na.omit() to delete all the NA values or use complete.cases

8条回答
  •  感动是毒
    2020-11-28 07:32

    In base R, we can select the columns which we want to test using grep, compare the data with 0, use rowSums to select rows which has all non-zero values.

    cols <- grep("^Mac", names(df))
    df[rowSums(df[cols] != 0) == length(cols), ]
    
    #          DateTime Mac1 Mac2 Mac3 Mac4
    #1 2011-04-02 06:05   21   21   21   21
    #2 2011-04-02 06:10   22   22   22   22
    #3 2011-04-02 06:20   24   24   24   24
    

    Doing this with inverted logic but giving the same output

    df[rowSums(df[cols] == 0) == 0, ]
    

    In dplyr, we can use filter_at to test for specific columns and use all_vars to select rows where all the values are not equal to 0.

    library(dplyr)
    df %>%  filter_at(vars(starts_with("Mac")), all_vars(. != 0))
    

    data

    df <- structure(list(DateTime = structure(1:6, .Label = c("2011-04-02 06:00", 
    "2011-04-02 06:05", "2011-04-02 06:10", "2011-04-02 06:15", "2011-04-02 06:20", 
    "2011-04-02 06:25"), class = "factor"), Mac1 = c(20L, 21L, 22L, 
    23L, 24L, 0L), Mac2 = c(0L, 21L, 22L, 23L, 24L, 25L), Mac3 = c(20L, 
    21L, 22L, 0L, 24L, 25L), Mac4 = c(20L, 21L, 22L, 23L, 24L, 0L
    )), class = "data.frame", row.names = c(NA, -6L))
    

提交回复
热议问题