rguides

How to Compute Row Percentages of Total in R

To compute row percentages of total, divide each value by the sum of all values in its group, then multiply by 100. This is a common summarization task in R, useful for frequency tables, budget breakdowns, and contribution analysis. The pattern works across base R, dplyr, and data.table with only minor syntax differences.

library(dplyr)

df <- data.frame(
  product = c("A", "B", "C", "D"),
  sales   = c(150, 300, 100, 450)
)

df %>% mutate(percentage = sales / sum(sales) * 100)
#   product sales percentage
# 1       A   150      15
# 2       B   300      30
# 3       C   100      10
# 4       D   450      45

For grouped percentages, add group_by() before mutate(): df |> group_by(category) |> mutate(pct = sales / sum(sales) * 100). Use na.rm = TRUE in sum() to handle missing values, and call ungroup() afterward to prevent grouping side effects. The base R equivalent is df$percentage <- df$sales / sum(df$sales) * 100, and data.table uses dt[, percentage := sales / sum(sales) * 100].

# Grouped percentages
df %>% group_by(category) %>% mutate(pct = sales / sum(sales) * 100)

# data.table approach
library(data.table)
dt[, percentage := sales / sum(sales) * 100]

For frequency tables, prop.table(table(x)) converts a count table to proportions in one call. Use margin = 1 for row proportions or margin = 2 for column proportions. The scales::percent() function formats decimal proportions as display-ready percentage strings. For cumulative percentages across ordered categories, cumsum(prop.table(table(x))) * 100 gives a running total that is useful for Pareto charts and contribution analysis.

See also