Home > Mobile >  Deleting rows with specific column values in dplyr
Deleting rows with specific column values in dplyr

Time:10-22

I wish to delete only those rows that contain a negative value in all the columns. For instance, take a look at my dataset as follows: So, I want to delete row 4 only.

Variable 1   Variable 2   Variable 3    Variable 4    Variable 5   Variable 6    Variable 7
   2            -9             4             3             2           3             5  
   3            -7             4             3             3           5             3
   4             5             5             1             5           3             2
  -5            -1            -9            -9            -7          -1            -6
  -9             3             3             2             3           4             3
  -5            -9             2             1             3           4             2
   3             2             1             5             5           5             1
   4             4            -3            -3             6           5             4

CodePudding user response:

Use either if_all and negate (!)

library(dplyr)
df1 <- df1 %>% 
   filter(!if_all(everything(), ~ . < 0))

Or make use of if_any

df1 <- df1 %>% 
    filter(if_any(everything(), ~ . >= 0))
df1
 Variable1 Variable2 Variable3 Variable4 Variable5 Variable6 Variable7
1         2        -9         4         3         2         3         5
2         3        -7         4         3         3         5         3
3         4         5         5         1         5         3         2
4        -9         3         3         2         3         4         3
5        -5        -9         2         1         3         4         2
6         3         2         1         5         5         5         1
7         4         4        -3        -3         6         5         4

data

df1 <- structure(list(Variable1 = c(2L, 3L, 4L, -5L, -9L, -5L, 3L, 4L
), Variable2 = c(-9L, -7L, 5L, -1L, 3L, -9L, 2L, 4L), Variable3 = c(4L, 
4L, 5L, -9L, 3L, 2L, 1L, -3L), Variable4 = c(3L, 3L, 1L, -9L, 
2L, 1L, 5L, -3L), Variable5 = c(2L, 3L, 5L, -7L, 3L, 3L, 5L, 
6L), Variable6 = c(3L, 5L, 3L, -1L, 4L, 4L, 5L, 5L), Variable7 = c(5L, 
3L, 2L, -6L, 3L, 2L, 1L, 4L)), class = "data.frame", row.names = c(NA, 
-8L))
  • Related