How to Create a Table by Group in R (Example Code)
In this tutorial, I’ll illustrate how to create a table with groups in the R programming language.
Creation of Example Data
data(iris) # Load 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 |
data(iris) # Load 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: Creating a Table with Groups
table(iris$Sepal.Length, # Make table by group iris$Species) # # setosa versicolor virginica # 4.3 1 0 0 # 4.4 3 0 0 # 4.5 1 0 0 # 4.6 4 0 0 # 4.7 2 0 0 # 4.8 5 0 0 # 4.9 4 1 1 # 5 8 2 0 # 5.1 8 1 0 # 5.2 3 1 0 # 5.3 1 0 0 # 5.4 5 1 0 # 5.5 2 5 0 # 5.6 0 5 1 # 5.7 2 5 1 # 5.8 1 3 3 # 5.9 0 2 1 # 6 0 4 2 # 6.1 0 4 2 # 6.2 0 2 2 # 6.3 0 3 6 # 6.4 0 2 5 # 6.5 0 1 4 # 6.6 0 2 0 # 6.7 0 3 5 # 6.8 0 1 2 # 6.9 0 1 3 # 7 0 1 0 # 7.1 0 0 1 # 7.2 0 0 3 # 7.3 0 0 1 # 7.4 0 0 1 # 7.6 0 0 1 # 7.7 0 0 4 # 7.9 0 0 1 |
table(iris$Sepal.Length, # Make table by group iris$Species) # # setosa versicolor virginica # 4.3 1 0 0 # 4.4 3 0 0 # 4.5 1 0 0 # 4.6 4 0 0 # 4.7 2 0 0 # 4.8 5 0 0 # 4.9 4 1 1 # 5 8 2 0 # 5.1 8 1 0 # 5.2 3 1 0 # 5.3 1 0 0 # 5.4 5 1 0 # 5.5 2 5 0 # 5.6 0 5 1 # 5.7 2 5 1 # 5.8 1 3 3 # 5.9 0 2 1 # 6 0 4 2 # 6.1 0 4 2 # 6.2 0 2 2 # 6.3 0 3 6 # 6.4 0 2 5 # 6.5 0 1 4 # 6.6 0 2 0 # 6.7 0 3 5 # 6.8 0 1 2 # 6.9 0 1 3 # 7 0 1 0 # 7.1 0 0 1 # 7.2 0 0 3 # 7.3 0 0 1 # 7.4 0 0 1 # 7.6 0 0 1 # 7.7 0 0 4 # 7.9 0 0 1