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

Updated on: 11-Nov-2021

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements