R Splitting Data Frame into List Based On Values of Common Variable (Example Code)
This post shows how to separate a large data frame into a list containing multiple data frames in R programming.
Example Data
data(iris) # Load iris head(iris) # Head of 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) # Load iris head(iris) # Head of 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: Splitting iris Data Set into Different Species
iris_list <- split(iris, f = iris$Species) # Split iris data set iris_list # Print iris as list # $setosa # 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 # ... # $versicolor # 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 # ... # $virginica # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 101 6.3 3.3 6.0 2.5 virginica # 102 5.8 2.7 5.1 1.9 virginica # 103 7.1 3.0 5.9 2.1 virginica # ... |
iris_list <- split(iris, f = iris$Species) # Split iris data set iris_list # Print iris as list # $setosa # 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 # ... # $versicolor # 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 # ... # $virginica # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 101 6.3 3.3 6.0 2.5 virginica # 102 5.8 2.7 5.1 1.9 virginica # 103 7.1 3.0 5.9 2.1 virginica # ...