How to Apply the split() & unsplit() Functions in R (2 Examples)
In this tutorial, I’ll illustrate how to apply the split and unsplit functions in the R programming language.
Example Data
data(iris) # Load 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 |
data(iris) # Load 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
Example 1: Splitting Data Frame Column Using split Function
iris_split <- split(iris$Sepal.Length, iris$Species) # Applying split() in R iris_split # Printing output of split function # $setosa # [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 ... # # $versicolor # [1] 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 ... # # $virginica # [1] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 ... |
iris_split <- split(iris$Sepal.Length, iris$Species) # Applying split() in R iris_split # Printing output of split function # $setosa # [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 ... # # $versicolor # [1] 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 ... # # $virginica # [1] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 ...
Example 2: Unsplitting Data Frame Column Using unsplit Function
iris_unsplit <- unsplit(iris_split, iris$Species) # Applying unsplit() in R iris_unsplit # Printing output of unsplit function # [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1 ... |
iris_unsplit <- unsplit(iris_split, iris$Species) # Applying unsplit() in R iris_unsplit # Printing output of unsplit function # [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1 ...
iris_unsplit == iris$Sepal.Length # Compare unsplit output with original data column # [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE ... |
iris_unsplit == iris$Sepal.Length # Compare unsplit output with original data column # [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE ...