sum()

sum(..., na.rm = FALSE)
Returns: numeric · Updated March 13, 2026 · Base Functions
arithmetic base statistics

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
...numericNumeric 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

# 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

# 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

# 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

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

Weighted sum

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

Check for overflow

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

See Also