How to subset rows of an R data frame if all columns have values greater than a certain value

R ProgrammingServer Side ProgrammingProgramming

To subset rows of an R data frame if all columns have values greater than a certain value, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use filter_all function of dplyr package with all_vars function to subset the rows of the data frame for all columns having values greater than a certain value.

Create the data frame

Let's create a data frame as shown below −

Example

 Live Demo

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
df<-data.frame(x1,x2,x3)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Output

      x1             x2       x3
1 -0.31376878 -0.12968316 0.8419411
2 -0.83862302 -1.55831805 0.5412468
3 -0.81062837 -0.28474741 0.9073120
4 -0.50831218 -0.62854883 -0.3554728
5 -0.02295662 -0.01396397 -0.3872239
6 0.53754325 -0.35212127 -1.0889800
7 0.15640887 0.13740119 1.0268027
8 -1.07725923 0.31228013 -0.1728887
9 -0.74389064 -1.27700154 -0.5637569
10 -0.18454349 -0.72006275 1.2916641
11 -0.02374880 -0.43866322 -0.2552326
12 0.36739652 -0.09626434 -0.3846456
13 -1.63167811 -1.78833172 -1.7815582
14 -0.12921857 -0.76465935 -1.0403800
15 0.36201061 0.85615242 -0.8595591
16 1.23294914 1.21579843 2.1846038
17 0.20417021 1.17202100 0.5694823
18 -1.36131961 -0.30325395 -0.6394704
19 0.47171837 -0.32342429 0.5026272
20 -2.04807109 1.16932268 -1.2727892

Subset the data frame

Loading dplyr package and using filter_all function all_vars function to subset the rows of the data frame df for all columns having values greater than -0.5 −

Example

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
df<-data.frame(x1,x2,x3)
library(dplyr)
df %>% filter_all(all_vars(.>-0.5))

Output

         x1          x2       x3
1 -0.31376878 -0.12968316 0.8419411
2 -0.02295662 -0.01396397 -0.3872239
3 0.15640887 0.13740119 1.0268027
4 -0.02374880 -0.43866322 -0.2552326
5 0.36739652 -0.09626434 -0.3846456
6 1.23294914 1.21579843 2.1846038
7 0.20417021 1.17202100 0.5694823
8 0.47171837 -0.32342429 0.5026272
raja
Published on 09-Aug-2021 09:00:18
Advertisements