Subset Rows of Data Frame in Range of Numbers in R (Example Code)
In this article you’ll learn how to select rows of a data frame in a particular range of numbers in a certain column in R.
Constructing Example Data
data(iris) # Loading example data frame 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 |
data(iris) # Loading example data frame 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: Applying filter() & between() Functions to Extract Data Frame Rows in Range of Numbers
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
iris_sub <- iris %>% # Selecting certain data frame rows dplyr::filter(dplyr::between(Sepal.Length, 5.0, 5.3)) iris_sub # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 5.0 3.6 1.4 0.2 setosa # 3 5.0 3.4 1.5 0.2 setosa # 4 5.1 3.5 1.4 0.3 setosa # 5 5.1 3.8 1.5 0.3 setosa # 6 5.1 3.7 1.5 0.4 setosa # 7 5.1 3.3 1.7 0.5 setosa # 8 5.0 3.0 1.6 0.2 setosa # 9 5.0 3.4 1.6 0.4 setosa # 10 5.2 3.5 1.5 0.2 setosa # 11 5.2 3.4 1.4 0.2 setosa # 12 5.2 4.1 1.5 0.1 setosa # 13 5.0 3.2 1.2 0.2 setosa # 14 5.1 3.4 1.5 0.2 setosa # 15 5.0 3.5 1.3 0.3 setosa # 16 5.0 3.5 1.6 0.6 setosa # 17 5.1 3.8 1.9 0.4 setosa # 18 5.1 3.8 1.6 0.2 setosa # 19 5.3 3.7 1.5 0.2 setosa # 20 5.0 3.3 1.4 0.2 setosa # 21 5.2 2.7 3.9 1.4 versicolor # 22 5.0 2.0 3.5 1.0 versicolor # 23 5.0 2.3 3.3 1.0 versicolor # 24 5.1 2.5 3.0 1.1 versicolor |
iris_sub <- iris %>% # Selecting certain data frame rows dplyr::filter(dplyr::between(Sepal.Length, 5.0, 5.3)) iris_sub # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 5.0 3.6 1.4 0.2 setosa # 3 5.0 3.4 1.5 0.2 setosa # 4 5.1 3.5 1.4 0.3 setosa # 5 5.1 3.8 1.5 0.3 setosa # 6 5.1 3.7 1.5 0.4 setosa # 7 5.1 3.3 1.7 0.5 setosa # 8 5.0 3.0 1.6 0.2 setosa # 9 5.0 3.4 1.6 0.4 setosa # 10 5.2 3.5 1.5 0.2 setosa # 11 5.2 3.4 1.4 0.2 setosa # 12 5.2 4.1 1.5 0.1 setosa # 13 5.0 3.2 1.2 0.2 setosa # 14 5.1 3.4 1.5 0.2 setosa # 15 5.0 3.5 1.3 0.3 setosa # 16 5.0 3.5 1.6 0.6 setosa # 17 5.1 3.8 1.9 0.4 setosa # 18 5.1 3.8 1.6 0.2 setosa # 19 5.3 3.7 1.5 0.2 setosa # 20 5.0 3.3 1.4 0.2 setosa # 21 5.2 2.7 3.9 1.4 versicolor # 22 5.0 2.0 3.5 1.0 versicolor # 23 5.0 2.3 3.3 1.0 versicolor # 24 5.1 2.5 3.0 1.1 versicolor
Related Tutorials
Below, you may find some further resources on topics such as indices, numeric values, variables, and vectors: