Home > Net >  R remove rows with condition rows contains negative values
R remove rows with condition rows contains negative values

Time:09-26

How to remove the rows in a dataframe which entire rows values are negative?

structure(list(name = c(1,-2,-6), data1 = c(1,-30,6), 
data3 = c(1,-51,-6), score1 = c(0, -40, 10), 
score2 = c(20, -25, 10)), class = "data.frame", 
row.names = c(NA, -3L))

output

name data1 data3 score1 score2
 1     1     1      0     20 
-6     6    -6     10     10

CodePudding user response:

Checking the rowSums if x > 0.

DF[rowSums(DF > 0) != 0, ]
#   name data1 data3 score1 score2
# 1    1     1     1      0     20
# 3   -6     6    -6     10     10

CodePudding user response:

You can use if_any from dplyr

library(dplyr)

df %>% 
  filter(if_any(.cols = everything(),.fns = ~. > 0))

  name data1 data3 score1 score2
1    1     1     1      0     20
2   -6     6    -6     10     10

CodePudding user response:

To filter out all rows in which all numeric values are negative, we should use across(where(is.numeric)) inside if_any.

library(dplyr)
df %>% filter(if_any(across(where(is.numeric), ~.x >=0))

CodePudding user response:

Using if_all and negate (!)

library(dplyr)
df1 %>%
   filter(!if_all(where(is.numeric), ~ .x < 0))
  name data1 data3 score1 score2
1    1     1     1      0     20
2   -6     6    -6     10     10
  •  Tags:  
  • r
  • Related