Table with Counts, Proportions & Percentages in R (Example Code)

In this R tutorial you’ll learn how to construct a contingency, proportion, and percentage matrix.

Creation of Example Data

data(iris)                                           # Iris data set as example
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: Create Contingency, Proportion & Percentage Matrix

iris_table <- round(rbind(table(iris$Sepal.Length),  # Constructing matrix
                   prop.table(table(iris$Sepal.Length)),
                   prop.table(table(iris$Sepal.Length)) * 100), 2)
rownames(iris_table) <- c("Count",                   # Renaming rows
                          "Proportion",
                          "Percentage")
iris_table                                           # Printing matrix to RStudio console
#             4.3  4.4  4.5  4.6  4.7  4.8  4.9     5  5.1  5.2  5.3  5.4  5.5  5.6  5.7  5.8  5.9    6  6.1  6.2  6.3  6.4  6.5  6.6  6.7  6.8  6.9    7  7.1  7.2  7.3  7.4  7.6  7.7  7.9
# Count      1.00 3.00 1.00 4.00 2.00 5.00 6.00 10.00 9.00 4.00 1.00 6.00 7.00 6.00 8.00 7.00 3.00 6.00 6.00 4.00 9.00 7.00 5.00 2.00 8.00 3.00 4.00 1.00 1.00 3.00 1.00 1.00 1.00 4.00 1.00
# Proportion 0.01 0.02 0.01 0.03 0.01 0.03 0.04  0.07 0.06 0.03 0.01 0.04 0.05 0.04 0.05 0.05 0.02 0.04 0.04 0.03 0.06 0.05 0.03 0.01 0.05 0.02 0.03 0.01 0.01 0.02 0.01 0.01 0.01 0.03 0.01
# Percentage 0.67 2.00 0.67 2.67 1.33 3.33 4.00  6.67 6.00 2.67 0.67 4.00 4.67 4.00 5.33 4.67 2.00 4.00 4.00 2.67 6.00 4.67 3.33 1.33 5.33 2.00 2.67 0.67 0.67 2.00 0.67 0.67 0.67 2.67 0.67

Leave a Reply

Your email address will not be published. Required fields are marked *

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