Filter Rows of Data Frame based on a Column

To filter rows of a data frame in R, based on a column, use the following expression.

</>
Copy
data_frame_name[condition, ]

Examples

</>
Copy
df[df['age'] > 10, ]
df[df['age'] == 10, ]
df[df['age'] < 10, ]

The above expression returns a data frame with the filtered rows, the rows that satisfy the given condition.

Examples

Get Rows where Column Value is greater than Specific Value

In the following example, we take a data frame in df, with three columns, and filter the rows of this data frame based on the column age, where the condition is age > 10.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 age = c(4, 8, 10, 14, 18, 10, 12),
                 income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))

result <- df[df['age'] > 10, ]
print(result)

Output

tutorialkart$ Rscript example.r
  name age income
4    D  14    1.9
5    E  18    1.5
7    G  12    1.7

Get Rows where Column Value is equal to Specific Value

In the following example, we take a data frame in df, with three columns, and filter the rows of this data frame based on the column age, where the condition is age == 10.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 age = c(4, 8, 10, 14, 18, 10, 12),
                 income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))

result <- df[df['age'] == 10, ]
print(result)

Output

tutorialkart$ Rscript example.r
  name age income
3    C  10    1.7
6    F  10    1.0

Get Rows where Column Value is less than Specific Value

In the following example, we take a data frame in df, with three columns, and filter the rows of this data frame based on the column age, where the condition is age < 10.

example.r

</>
Copy
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 age = c(4, 8, 10, 14, 18, 10, 12),
                 income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))

result <- df[df['age'] < 10, ]
print(result)

Output

tutorialkart$ Rscript example.r
  name age income
1    A   4    1.6
2    B   8    1.5

We can use other relational operators as well like Not-Equal-to, Greater than or equal to, Less than or equal to, etc., in forming the condition.

Conclusion

In this R Tutorial, we learned how to filter the rows of a data frame based on the values of a single column, with the help of an example programs.