rguides

sum()

sum(..., na.rm = FALSE)

The sum() function computes the sum of all values in its arguments. It is one of the most frequently used functions in R for numerical analysis, statistics, and data manipulation. The function handles vectors, matrices, and can work across multiple arguments or a single iterable.

Syntax

sum(..., na.rm = FALSE)

Parameters

ParameterTypeDefaultDescription
...numeric,Numeric vectors, matrices, or individual values to sum
na.rmlogicalFALSEIf TRUE, missing values (NA) are removed before calculation

Examples

Basic usage

# Sum of a numeric vector
x <- c(1, 2, 3, 4, 5)
sum(x)
# [1] 15

Handling missing values

sum() treats NA as an unknown quantity: adding an unknown to any total produces an unknown, so sum(c(1, 2, NA, 4, 5)) returns NA. Setting na.rm = TRUE tells R to skip the missing entries and sum only the values that are present, which is usually what you want for descriptive statistics on real-world data.

# Without na.rm (returns NA)
y <- c(1, 2, NA, 4, 5)
sum(y)
# [1] NA

# With na.rm = TRUE
sum(y, na.rm = TRUE)
# [1] 12

Multiple arguments

Passing multiple vectors to sum() is equivalent to concatenating them first and then summing: sum(a, b) gives the same result as sum(c(a, b)). This variadic interface is convenient when your data arrives in separate variables rather than a single container, and it avoids the need to call c() explicitly.

# Sum multiple vectors
a <- c(1, 2, 3)
b <- c(4, 5, 6)
sum(a, b)
# [1] 21

# Equivalent to sum(c(a, b))

Summing matrices

When you pass a matrix to sum(), it flattens all elements and returns a single total. For row-wise or column-wise sums, rowSums() and colSums() are much faster than apply() with sum because they operate in compiled C code without the per-cell function-call overhead that apply() incurs.

# Sum all elements in a matrix
m <- matrix(1:9, nrow = 3)
sum(m)
# [1] 45

# Row and column sums
rowSums(m)
# [1] 12 15 18

colSums(m)
# [1] 12 15 18

Common patterns

Cumulative sum

cumsum() returns a vector the same length as its input, where each position holds the sum of all values up to and including that position. It is essentially sum() applied to progressively longer prefixes of the vector, and it is the foundation for running totals, accumulation curves, and cumulative distribution functions.

x <- c(5, 10, 15, 20)
cumsum(x)
# [1]  5 15 30 50

Weighted sum

A weighted sum multiplies each value by a corresponding weight before adding. In R this is simply sum(values * weights) — element-wise multiplication pairs each value with its weight, and sum() adds the products. This is the core calculation behind weighted means and expectation values in probability.

values <- c(10, 20, 30)
weights <- c(0.2, 0.5, 0.3)
sum(values * weights)
# [1] 19

Check for overflow

For integer vectors, sum() returns an integer result, which can overflow silently at values above roughly 2.1 billion. When working with large counts or aggregating many rows, convert to double first with as.double() to stay safe. For most everyday sums — small to moderate counts of typical values — overflow is not a concern, but it is worth knowing the limit exists.

# For very large numbers, consider using vapply for safety
x <- rep(1e300, 100)
# sum(x) returns Inf
# sum(x) / 100 gives mean approximation

sum() in practice

sum() adds all elements of its input vectors. sum(c(1,2,3)) returns 6. It accepts multiple arguments: sum(a, b, c) adds all elements across all inputs. For logical vectors, TRUE is treated as 1 and FALSE as 0, making sum(condition) a concise way to count TRUE values: sum(x > 0) counts positive values.

With na.rm = TRUE, sum() skips NA values. Without it, any NA in the input returns NA. This default is intentional — NA represents unknown values, and the sum of a set that includes unknowns is also unknown unless you explicitly decide to ignore the unknowns.

cumsum() computes the running cumulative sum. rowSums() and colSums() compute sums across rows or columns of a matrix, and are faster than apply(m, 1, sum) or apply(m, 2, sum) because they are implemented in C. For data frames, rowSums(df[, numeric_cols]) sums numeric columns row-wise.

Integer overflow: sum() on an integer vector returns an integer, which overflows at approximately 2.1 billion. sum(rep(1L, 3e9)) produces NA with a warning. To avoid overflow, convert to double first: sum(as.double(large_integer_vector)). For most practical sums of typical integer data (e.g., row counts, event counts), overflow is not a concern.

sum() accepts any number of arguments: sum(1, 2, 3) and sum(c(1, 2, 3)) both return 6. With na.rm = FALSE (default), any NA in the input produces NA. sum(logical_vector) counts TRUE values since TRUE coerces to 1. For column sums of a matrix, colSums() is faster than apply(m, 2, sum) because it is implemented in C without the overhead of apply().

See also

  • mean()
  • cumsum() rowSums(is.na(df)) counts NA values per row across all columns by exploiting the fact that TRUE coerces to 1.sum() with na.rm = TRUE ignores NA values and returns the sum of the remaining elements. Called on a zero-length vector, sum(integer(0)) returns 0 — the identity element for addition. cumsum() computes a running cumulative sum. For column sums of a matrix or data frame, colSums() is faster than apply(m, 2, sum) because it avoids the apply overhead. tabulate(x) is faster than table(x) for non-negative integer vectors when only counts are needed.