# How to select rows based on range of values of a column in an R data frame?

Extraction or selection of data can be done in many ways such as based on an individual value, range of values, etc. This is mostly required when we want to either compare the subsets of the data set or use the subset for analysis. The selection of rows based on range of value may be done for testing as well. We can do this by subset function.

## Example

Consider the below data frame −

Live Demo

> x1<-rpois(20,2)
> x2<-rpois(20,5)
> x3<-rpois(20,10)
> df<-data.frame(x1,x2,x3)
> df

## Output

 x1 x2 x3
1 3 2 6
2 3 4 9
3 4 4 12
4 4 8 12
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
12 0 2 5
13 2 6 12
14 2 4 16
15 0 8 14
16 4 1 5
17 1 7 12
18 3 5 9
19 1 6 3
20 0 3 4
> subset(df,df$x1>0 & df$x1<4)

## Output

 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<4)

## Output

 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
6 2 1 9
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
18 3 5 9
19 1 6 3
> subset(df,df$x1>=1 & df$x1<3)

## Output

 x1 x2 x3
6 2 1 9
8 1 5 12
9 1 4 5
11 2 6 15
13 2 6 12
14 2 4 16
17 1 7 12
19 1 6 3
> subset(df,df$x1>2 & df$x1<=3)

## Output

 x1 x2 x3
1 3 2 6
2 3 4 9
5 3 5 11
7 3 5 8
10 3 3 5
18 3 5 9
> subset(df,df$x2>2 & df$x2<6)

## Output

 x1 x2 x3
2 3 4 9
3 4 4 12
5 3 5 11
7 3 5 8
8 1 5 12
9 1 4 5
10 3 3 5
14 2 4 16
18 3 5 9
20 0 3 4
> subset(df,df$x3>2 & df$x3<11)

## Output

 x1 x2 x3
1 3 2 6
2 3 4 9
6 2 1 9
7 3 5 8
9 1 4 5
10 3 3 5
12 0 2 5
16 4 1 5
18 3 5 9
19 1 6 3
20 0 3 4