Open In App

Select DataFrame Rows where Column Values are in Range in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to select dataframe rows where column values are in a range in R programming language.

Data frame indexing can be used to extract rows or columns from the dataframe. The condition can be applied to the specific columns of the dataframe and combined using the logical operator. The logical values in terms of TRUE or FALSE are returned where the TRUE  values indicate the rows satisfying the condition. The selected rows are then extracted using the returned row indexes. 

Syntax:

dataframe[condition to define range]

Example: Select rows where column values are in the range

R




# create first dataframe
data_frame1 < -data.frame(col1=c(rep('Grp1', 2),
                                 rep('Grp2', 2),
                                 rep('Grp3', 2)),
                          col2=rep(1: 3, 2),
                          col3=rep(1: 2, 3),
                          col4=letters[1:6]
                          )
  
print("Original DataFrame")
print(data_frame1)
  
filtered_rows < - data_frame1$col2 >= 2 & data_frame1$col2 < 4
data_frame_mod < - data_frame1[filtered_rows, ]
  
print("Extracted DataFrame")
print(data_frame_mod)


Output:

[1] "Original DataFrame" 
col1 col2 col3 col4 
1 Grp1    1    1    a 
2 Grp1    2    2    b 
3 Grp2    3    1    c 
4 Grp2    1    2    d 
5 Grp3    2    1    e 
6 Grp3    3    2    f 
[1] "Extracted DataFrame" 
col1 col2 col3 col4 
2 Grp1    2    2    b 
3 Grp2    3    1    c 
5 Grp3    2    1    e 
6 Grp3    3    2    f

Conditions can also be applied over multiple columns of the dataframe and connected using a logical operator. 

Example: Selecting columns by applying conditions over multiple columns. 

R




# create first dataframe
data_frame1<-data.frame(col1=c(rep('Grp1',2),
                               rep('Grp2',2),
                               rep('Grp3',2)), 
                        col2=rep(1:3,2),
                        col3=rep(1:2,3),
                        col4 = letters[1:6]
                        )
  
print("Original DataFrame")
print(data_frame1)
  
filtered_rows <- data_frame1$col4 == 'a' | data_frame1$col3==2
data_frame_mod <- data_frame1[filtered_rows ,]
  
print("Extracted DataFrame")
print(data_frame_mod)


Output:

[1] "Original DataFrame" 
col1 col2 col3 col4 
1 Grp1    1    1    a 
2 Grp1    2    2    b 
3 Grp2    3    1    c 
4 Grp2    1    2    d 
5 Grp3    2    1    e 
6 Grp3    3    2    f 
[1] "Extracted DataFrame" 
 col1 col2 col3 col4 
1 Grp1    1    1    a 
2 Grp1    2    2    b 
4 Grp2    1    2    d 
6 Grp3    3    2    f


Last Updated : 23 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads