R Extract Rows of Data Frame by Factor Levels (2 Examples)

This article explains how to extract rows according to factor levels in R.

Creation of Example Data

data(iris)                                # Loading 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 1: Subset Rows According to One Specific Factor Level

iris_subset1 <- iris[iris$Species ==      # Extract one factor level
                       "versicolor", ]
head(iris_subset1)                        # Show new data
#    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

Example 2: Subset Rows According to Several Different Factor Levels

iris_subset2 <- iris[iris$Species %in%    # Extract multiple factor levels
                       c("setosa", "versicolor"), ]
head(iris_subset2)                        # Show new 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

Related Articles & Further Resources

You may find some related R programming language tutorials on topics such as variables, loops, and matrices below:

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