Applying the which() Function to a Data Frame in R (Example Code)

This post demonstrates how to apply the which function to a data frame in R programming.

Construction of Example Data

data(iris)                                            # Example 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: Extract Certain Rows of Data Frame Using which() Function

iris_subset <- iris[which(iris$Sepal.Length >= 7), ]  # Logical condition in which function
iris_subset
#     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

Leave a Reply

Your email address will not be published.

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