Learn R Programming

base (version 3.3.2)

sum: Sum of Vector Elements

Description

sum returns the sum of all the values present in its arguments.

Usage

sum(…, na.rm = FALSE)

Arguments

numeric or complex or logical vectors.
na.rm
logical. Should missing values (including NaN) be removed?

Value

The sum. If all of are of type integer or logical, then the sum is integer, and in that case the result will be NA (with a warning) if integer overflow occurs. Otherwise it is a length-one numeric or complex vector. NB: the sum of an empty set is zero, by definition.

S4 methods

This is part of the S4 Summary group generic. Methods for it must use the signature x, …, na.rm. ‘plotmath’ for the use of sum in plot annotation.

Details

This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments should be unnamed, and dispatch is on the first argument. If na.rm is FALSE an NA or NaN value in any of the arguments will cause a value of NA or NaN to be returned, otherwise NA and NaN values are ignored. Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0). Loss of accuracy can occur when summing values of different signs: this can even occur for sufficiently long integer inputs if the partial sums would cause integer overflow. Where possible extended-precision accumulators are used, but this is platform-dependent.

References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

See Also

colSums for row and column sums.

Examples

Run this code

## Pass a vector to sum, and it will add the elements together.
sum(1:5)

## Pass several numbers to sum, and it also adds the elements.
sum(1, 2, 3, 4, 5)

## In fact, you can pass vectors into several arguments, and everything gets added.
sum(1:2, 3:5)

## If there are missing values, the sum is unknown, i.e., also missing, ....
sum(1:5, NA)
## ... unless  we exclude missing values explicitly:
sum(1:5, NA, na.rm = TRUE)

Run the code above in your browser using DataLab