Skip to main content
v2026.11,986 entries · CC-BY 4.0

Weighted Mean in R: weighted.mean() Syntax, NA Rules and Worked Example

How to calculate a weighted mean in R with weighted.mean(): arguments, worked examples with arithmetic, and how NA values and zero weights behave.

Written and maintained by CASRAI Editorial Board

Published

On this page

In R, the weighted mean is calculated with weighted.mean(x, w) from the base stats package: x holds the values, w holds one weight per value, and the function returns a single number equal to the sum of each value times its weight, divided by the sum of the weights. Missing values in x are dropped only when you set na.rm = TRUE, and a missing value in w always makes the result missing.

What it is used for in research

A weighted mean is the right summary whenever the values you are averaging do not carry equal evidential weight. Typical research cases are pooling the mean scores of study sites that enrolled different numbers of participants, averaging grouped data where each class has its own frequency, and combining per-item scores that count for different shares of a total, such as the credit hours behind each course grade in the example in R’s own documentation. The arithmetic is the same one used by hand for the mean of a frequency distribution table and for the mean read from a histogram, where the weights are the class frequencies and the values are class midpoints (see class midpoint).

The formula is: weighted mean = (w1x1 + w2x2 + … + wnxn) / (w1 + w2 + … + wn). Because the weights are divided by their own total, the R documentation notes that they are normalized to sum to one. In practice this means weights supplied as counts (5, 5, 4, 1) and weights supplied as proportions (5/15, 5/15, 4/15, 1/15) give exactly the same answer.

Install or access

weighted.mean() belongs to the stats package that ships with R, so there is nothing extra to install. R itself is obtained from CRAN: the R Installation and Administration manual states that sources, binaries and documentation for R can be obtained via CRAN, with Windows binaries under bin/windows of a CRAN site and macOS builds reached from the “Download R for (Mac) OS X” link on the CRAN front page. Linux binaries are provided for some distributions.

The only function on this page that needs an add-on package is the row and column version in matrixStats. Install it once from CRAN with install.packages("matrixStats") and load it with library(matrixStats). To read the manual page for the base function from inside R, run ?weighted.mean.

Step-by-step: calculate a weighted mean in R

Step 1: state the function and its arguments

The documented usage is weighted.mean(x, w, ...), and the default method is weighted.mean(x, w, ..., na.rm = FALSE). The arguments are:

  • x: an object containing the values whose weighted mean is to be computed.
  • w: a numeric vector of weights the same length as x. If w is omitted, every element gets the same weight, so the result equals the ordinary mean.
  • na.rm: a logical value. If TRUE, NA values in x are removed before the computation. The default is FALSE.

Step 2: put values and weights in two vectors

The documentation’s own example computes a grade point average from four course grades, using the credit hours as weights:

x  = c(3.7, 3.3, 3.5, 2.8)
wt = c(5, 5, 4, 1)
weighted.mean(x, wt)
# [1] 3.453333

By hand: (3.7 × 5 + 3.3 × 5 + 3.5 × 4 + 2.8 × 1) / (5 + 5 + 4 + 1) = (18.5 + 16.5 + 14 + 2.8) / 15 = 51.8 / 15 = 3.4533. The unweighted mean(x) is 13.3 / 4 = 3.325, so weighting by credit hours moves the result up because the two highest grades carry the most credit.

Step 3: use a data frame column as the weights

Research data usually arrive in a table. The next example is an illustrative composite with invented numbers, not real study results: mean test scores for three sites, with the number of participants at each site as the weight.

sites = data.frame(
  site  = c("A", "B", "C"),
  score = c(72, 65, 80),
  n     = c(120, 30, 50)
)
weighted.mean(sites$score, sites$n)
# [1] 72.95
mean(sites$score)
# [1] 72.33333

By hand: (72 × 120 + 65 × 30 + 80 × 50) / (120 + 30 + 50) = (8640 + 1950 + 4000) / 200 = 14590 / 200 = 72.95. The plain mean treats the 30-person site as equal to the 120-person site; the weighted mean does not. This is the usual reason to prefer weighted.mean() when pooling group means.

Step 4: compute a weighted mean for each group

weighted.mean() returns one number, so for subgroups split the data and apply the function to each piece. This example is again illustrative data:

d = data.frame(
  group = c("A", "A", "B", "B"),
  score = c(70, 80, 60, 90),
  w     = c(1, 3, 2, 2)
)
sapply(split(d, d$group), function(g) weighted.mean(g$score, g$w))
#    A    B
# 77.5 75.0

By hand, group A: (70 × 1 + 80 × 3) / 4 = 310 / 4 = 77.5. Group B: (60 × 2 + 90 × 2) / 4 = 300 / 4 = 75. For a related task, the per-row group mean without collapsing the table, see ave() in R.

Step 5: weighted means of every row or column of a matrix

The matrixStats package provides rowWeightedMeans() and colWeightedMeans(). Both have the signature (x, w = NULL, rows = NULL, cols = NULL, na.rm = FALSE, ..., useNames = TRUE). For the column version w has one weight per row of x; for the row version it has one weight per column. If no weights are given, the function falls back to rowMeans() or colMeans().

library(matrixStats)
m = matrix(c(1, 2, 3, 4, 5, 6), nrow = 3)
colWeightedMeans(m, w = c(1, 1, 2))
# [1] 2.25 5.25

By hand, first column: (1 × 1 + 2 × 1 + 3 × 2) / 4 = 9 / 4 = 2.25; second column: (4 + 5 + 12) / 4 = 21 / 4 = 5.25.

Output and how to read it

The default method returns a numeric vector of length one, printed by R with seven significant digits (for example 3.453333). Interpret it as the average of x in which each value counts in proportion to its weight. Three points help avoid misreading it:

  • Scale of weights does not matter, ratios do. Doubling every weight leaves the answer unchanged, because weights are normalized.
  • It is a point estimate only. The function returns just the mean, with no standard error or confidence interval.
  • The result lies between the smallest and largest value of x that has a non-zero weight. If your result falls outside that range, check that values and weights are aligned element by element.

When you report the result, state what the weights were (participants, credit hours, class frequencies) so a reader can reproduce it.

Troubleshooting: NA values, zero weights and mismatched lengths

Each behaviour in the table below is stated in the R manual page for weighted.mean except the numeric results, which are worked by hand from the documented rules.

Situation What R does Example
NA in x, default na.rm = FALSE The result is NA weighted.mean(c(3.7, NA, 3.5, 2.8), c(5, 5, 4, 1)) gives NA
NA in x, na.rm = TRUE The NA values in x are removed before computing, and the remaining weights are renormalized The same call with na.rm = TRUE gives (18.5 + 14 + 2.8) / 10 = 3.53
NA in w Not handled specially, so the result is missing, and na.rm does not rescue it weighted.mean(c(3.7, 3.3), c(5, NA)) gives NA
A zero weight Handled specially: the corresponding value of x is omitted from the sum weighted.mean(c(3.7, NA, 3.5), c(5, 0, 4)) gives (18.5 + 14) / 9 = 3.611111
Weights sum to zero or infinity The result is likely NaN All weights set to 0
No w supplied All elements get the same weight, so the answer equals mean(x) weighted.mean(c(2, 4, 6)) gives 4

Two practical consequences follow. First, a missing weight is a data problem you must fix upstream: na.rm = TRUE only addresses missing values in x. Second, because zero-weight observations are dropped before the sum, an NA value in x that has weight zero does not poison the result, which is handy when a weight column has been set to zero for excluded cases. If you suspect that values are missing for systematic reasons rather than at random, read MCAR, MAR and MNAR: diagnosing your missing data before simply removing them.

The documentation states that w must be the same length as x. If your values and weights come from different tables, merge them on a key first so the rows align; a length mismatch is an error to fix, not something to work around with recycling.

All three functions below are free and open source, and each is documented on the pages listed under Sources. The data table below compares their weight arguments, required weight lengths and what they return, compiled from those manual pages.

  • stats::weighted.mean() is the default choice for a single vector.
  • matrixStats::colWeightedMeans() and rowWeightedMeans() compute many weighted means in one call over the columns or rows of a matrix.
  • stats::cov.wt() estimates a weighted covariance matrix. Its wt argument takes non-negative weights, not all zero, with one weight per row of the data. With the default center = TRUE, it uses each variable’s weighted mean as the center, and the returned list contains cov, center, n.obs, wt and (when requested) cor. Its method argument is "unbiased" by default or "ML"; with equal weights of 1/n the unbiased estimate reduces to the usual n – 1 divisor.

For comparing R with other statistical packages in general, see SPSS vs. R for statistical analysis.

Sources

Data: Weighted-mean functions in R compared: weights argument, weight length and return value

Compares the free R functions that compute weighted means or weighted centres: weighted.mean in stats, colWeightedMeans and rowWeightedMeans in matrixStats, and cov.wt in stats. Compiled from the R stats manual pages and the CRAN matrixStats reference manual, giving the weights argument, the required weight length and what each returns.

Period covered: 2026.

Weighted-mean functions in R compared: weights argument, weight length and return value
FunctionPackageWeights argumentRequired weight lengthReturns / default without weights
weighted.meanstatswSame length as xNumeric vector of length one; equal weights if w is omitted
colWeightedMeansmatrixStatsw (default NULL)N, one per row of the N x K matrix xWeighted mean of each column; falls back to colMeans() if no weights are given
rowWeightedMeansmatrixStatsw (default NULL)K, one per column of the N x K matrix xWeighted mean of each row; falls back to rowMeans() if no weights are given
cov.wtstatswtEqual to nrow(x); non-negative, not all zeroList with cov, center, n.obs, wt and cor; center holds the weighted means when center = TRUE

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Weighted Mean in R: weighted.mean() Syntax, NA Rules and Worked Example

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →