filtering with multiple conditions on many columns using dplyr

前端 未结 7 1441
野趣味
野趣味 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:44

    First we create an index of all numeric columns. Then we subset all columns greater or equal than zero. So there is no need to check the column names, and the column id will be always positive.

    nums <- sapply(df, is.numeric)
    df[apply(df[, nums], MARGIN = 1, function(x) all(x >= 0)), ]
    

    Output:

      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
    

提交回复
热议问题