- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to subset R data frame rows if at least one or more values matches?
To subset R data frame rows if at least one or more values matches, we can follow the below steps −
First of all, create a data frame.
Then, use rowSums function along with sapply function and values for match to subset the data frame rows if at least one or more values matches.
Example
Create the data frame
Let’s create a data frame as shown below −
x<-rpois(25,5) y<-rpois(25,5) z<-rpois(25,5) df<-data.frame(x,y,z) df
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y z 1 5 5 2 2 10 5 5 3 3 4 6 4 9 4 12 5 2 4 5 6 3 4 4 7 4 3 9 8 4 5 10 9 5 3 9 10 3 2 2 11 2 8 4 12 4 5 2 13 2 9 2 14 5 2 1 15 6 2 7 16 2 4 7 17 7 5 5 18 3 3 1 19 4 4 7 20 7 4 5 21 4 4 4 22 3 6 2 23 3 2 7 24 1 3 3 25 5 4 4
Subset the data frame
Using rowSums function along with sapply function and values 4,5,6,7,8 for match to subset the data frame rows if at least one or more of these values matches −
x<-rpois(25,5) y<-rpois(25,5) z<-rpois(25,5) df<-data.frame(x,y,z) df[rowSums(sapply(df[], '%in%', c(4,5,6,7,8)))>0,]
Output
x y z 1 5 5 2 2 10 5 5 3 3 4 6 4 9 4 12 5 2 4 5 6 3 4 4 7 4 3 9 8 4 5 10 9 5 3 9 11 2 8 4 12 4 5 2 14 5 2 1 15 6 2 7 16 2 4 7 17 7 5 5 19 4 4 7 20 7 4 5 21 4 4 4 22 3 6 2 23 3 2 7 25 5 4 4
- Related Articles
- How to remove rows from an R data frame that contains at least one NaN?
- How to subset an R data frame if one of the supplied grouping values is found?
- How to subset rows of an R data frame if any columns have values greater than a certain value?
- How to subset rows of an R data frame if all columns have values greater than a certain value
- How to subset rows of an R data frame using grepl function?
- How to subset rows of an R data frame based on duplicate values in a particular column?
- How to subset rows of data frame without NA using dplyr in R?
- How to subset non-duplicate values from an R data frame column?
- How to subset R data frame rows and keep the rows with NA in the output?
- How to aggregate two lists if at least one element matches in MongoDB?
- How to subset an R data frame based on string values of a columns with OR condition?
- How to subset a data frame based on a vector values in R?
- How to subset row values based on columns name in R data frame?
- How to remove rows that contain at least one 0 in R?
- How to subset rows that contains maximum depending on another column in R data frame?

Advertisements