R Extract Rows If First Variable is Smaller Than Second (Example Code)

This article shows how to filter certain rows based on the values in two columns in R programming.

Creation of Example Data

data(iris)                                       # Load iris data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example: Filtering Rows of Data Frame by Logical Condition

iris[iris$Sepal.Width <= iris$Petal.Length, ]    # Specifying logical condition
#     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 51           7.0         3.2          4.7         1.4 versicolor
# 52           6.4         3.2          4.5         1.5 versicolor
# 53           6.9         3.1          4.9         1.5 versicolor
# 54           5.5         2.3          4.0         1.3 versicolor
# 55           6.5         2.8          4.6         1.5 versicolor
# 56           5.7         2.8          4.5         1.3 versicolor
# ...          ...         ...          ...         ... ...

Further Resources & Related Tutorials

Please find some further R programming tutorials on topics such as data inspection, extracting data, and naming data in the following list:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top