R Select Rows of Data Frame that don’t Match a Certain Condition (Example Code)
In this R programming tutorial you’ll learn how to select data frame rows that have no match to a certain condition.
Creation of Example Data
data(iris) # Iris as example data frame head(iris) # First six rows of iris data # 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 |
data(iris) # Iris as example data frame head(iris) # First six rows of iris data # 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: Apply subset() Function to Extract Certain Data Frame Rows that don’t Match a Condition
iris_new <- subset(iris, iris$Sepal.Length >= 7) # Extracting data frame rows iris_new # Show new data frame in RStudio # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 51 7.0 3.2 4.7 1.4 versicolor # 103 7.1 3.0 5.9 2.1 virginica # 106 7.6 3.0 6.6 2.1 virginica # 108 7.3 2.9 6.3 1.8 virginica # 110 7.2 3.6 6.1 2.5 virginica # 118 7.7 3.8 6.7 2.2 virginica # 119 7.7 2.6 6.9 2.3 virginica # 123 7.7 2.8 6.7 2.0 virginica # 126 7.2 3.2 6.0 1.8 virginica # 130 7.2 3.0 5.8 1.6 virginica # 131 7.4 2.8 6.1 1.9 virginica # 132 7.9 3.8 6.4 2.0 virginica # 136 7.7 3.0 6.1 2.3 virginica |
iris_new <- subset(iris, iris$Sepal.Length >= 7) # Extracting data frame rows iris_new # Show new data frame in RStudio # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 51 7.0 3.2 4.7 1.4 versicolor # 103 7.1 3.0 5.9 2.1 virginica # 106 7.6 3.0 6.6 2.1 virginica # 108 7.3 2.9 6.3 1.8 virginica # 110 7.2 3.6 6.1 2.5 virginica # 118 7.7 3.8 6.7 2.2 virginica # 119 7.7 2.6 6.9 2.3 virginica # 123 7.7 2.8 6.7 2.0 virginica # 126 7.2 3.2 6.0 1.8 virginica # 130 7.2 3.0 5.8 1.6 virginica # 131 7.4 2.8 6.1 1.9 virginica # 132 7.9 3.8 6.4 2.0 virginica # 136 7.7 3.0 6.1 2.3 virginica
Related Tutorials & Further Resources
Here, you can find some additional resources on topics such as character strings, vectors, and extracting data.