filtering with multiple conditions on many columns using dplyr

前端 未结 7 1438
野趣味
野趣味 2021-01-02 02:05

I\'ve searched on SO trying to find a solution to no avail. So here it is. I have a data frame with many columns, some of which are numerical and should be non-negative. I w

7条回答
  •  囚心锁ツ
    2021-01-02 02:43

    Using base R to get your result

    cond <- df[, grepl("_num$", colnames(df))] >= 0
    df[apply(cond, 1, function(x) {prod(x) == 1}), ]
    
      id  sth1 tg1_num sth2 tg2_num others
    1  1  dave       2   ca      35    new
    4  4 leroy       0   az      25    old
    5  5 jerry       4   mi      55    old
    

    Edit: this assumes you have multiple columns with "_num". It won't work if you have just one _num column

提交回复
热议问题