Extract Rows from Data Frame According to Vector in R (Example Code)

This article illustrates how to extract certain rows of a data frame according to the values in a vector in the R programming language.

Introduction of Example Data

data(iris)                                      # Loading & head of 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
filter_vector <- c(4.5, 5.0, 5.5)               # Vector for filtering
filter_vector                                   # Printing vector to RStudio console
# [1] 4.5 5.0 5.5

Example: Selecting Data Frame Rows Using %in%-Operator

iris[iris$Sepal.Length %in% filter_vector, ]    # Using %in%-operator in R
#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# 5           5.0         3.6          1.4         0.2     setosa
# 8           5.0         3.4          1.5         0.2     setosa
# 26          5.0         3.0          1.6         0.2     setosa
# 27          5.0         3.4          1.6         0.4     setosa
# 34          5.5         4.2          1.4         0.2     setosa
# 36          5.0         3.2          1.2         0.2     setosa
# 37          5.5         3.5          1.3         0.2     setosa
# 41          5.0         3.5          1.3         0.3     setosa
# 42          4.5         2.3          1.3         0.3     setosa
# 44          5.0         3.5          1.6         0.6     setosa
# 50          5.0         3.3          1.4         0.2     setosa
# 54          5.5         2.3          4.0         1.3 versicolor
# 61          5.0         2.0          3.5         1.0 versicolor
# 81          5.5         2.4          3.8         1.1 versicolor
# 82          5.5         2.4          3.7         1.0 versicolor
# 90          5.5         2.5          4.0         1.3 versicolor
# 91          5.5         2.6          4.4         1.2 versicolor
# 94          5.0         2.3          3.3         1.0 versicolor

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