How to subset rows based on criterion of multiple numerical columns in R data frame?



If we want to create a subset of a data frame based on multiple numerical columns then we can follow the below steps −

  • Creating a data frame.
  • Subsetting the data frame with the help of filter function of dplyr package.

Create the data frame

Let's create a data frame as shown below −

 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) −

      x1          x2         x3 1 0.24608371 -1.67514259 1.56498827 2 -0.20224892 -0.39720395 0.59500832 3 0.17826481 -0.83163497 1.78149860 4 0.11038442 0.09988394 -1.14734732 5 0.22454610 0.17475117 -0.52450684 6 -0.48267933 0.42938131 -1.16455384 7 -0.21522654 0.70470856 -0.27026051 8 1.03643685 -1.41827019 2.37306776 9 -0.08207666 1.07401006 -0.46598763 10 0.57203386 0.19795135 -1.65466371 11 0.22204629 -1.11419199 -1.33215677 12 -0.10529923 1.11458884 2.10602322 13 1.27808674 0.22931036 0.45067492 14 -0.27898456 -0.15679337 0.50367422 15 -0.48424097 -0.75060607 0.33437543 16 -0.04662138 1.62810538 0.02225197 17 2.08021754 0.60111386 0.94291531 18 -0.38586764 0.91240768 -1.05151779 19 -2.00167901 1.98869632 1.22709542 20 -0.01869414 1.13392687 -0.37114340

Subsetting the data frame

Loading dplyr package and subsetting df if all columns are greater than -0.5 −

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

Output

        x1        x2       x3 1 -0.20224892 -0.3972039  0.59500832 2 -0.21522654  0.7047086  -0.27026051 3 -0.08207666  1.0740101  -0.46598763 4 -0.10529923  1.1145888  2.10602322 5  1.27808674  0.2293104 0.45067492 6 -0.27898456 -0.1567934  0.50367422 7 -0.04662138  1.6281054  0.02225197 8  2.08021754  0.6011139  0.94291531 9 -0.01869414  1.1339269 -0.37114340
Updated on: 2021-08-13T11:33:31+05:30

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements