How to Apply the expand.grid() Function in R (Example Code)

In this R tutorial you’ll learn how to return each combination of two variables using the expand.grid function.

Example Data

data(iris)                       # Example data
iris_sel <- iris[c(1, 51, 101), c(1, 5)]
iris_sel
#     Sepal.Length    Species
# 1            5.1     setosa
# 51           7.0 versicolor
# 101          6.3  virginica

Example: Apply expand.grid() Function to Data Frame Columns

expand.grid(iris_sel$Species,    # Using expand.grid function
            iris_sel$Sepal.Length)
#         Var1 Var2
# 1     setosa  5.1
# 2 versicolor  5.1
# 3  virginica  5.1
# 4     setosa  7.0
# 5 versicolor  7.0
# 6  virginica  7.0
# 7     setosa  6.3
# 8 versicolor  6.3
# 9  virginica  6.3

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