R sum() Function - Calculating the Sum
The R sum() function is used to calculate the sum of all elements in a vector or matrix.
When doing summary statistics on data, sum() is one of the most commonly used functions.
The syntax of the sum() function is as follows:
sum(x, na.rm = FALSE)
Parameter Description:
-
x An input vector, matrix, or column of a data frame.
-
na.rm A boolean, defaults to FALSE, setting whether to remove missing values NA. Set to TRUE to ignore NA when calculating the sum.
Example
Create a vector
x
<-
c
(
12
,
27
,
3
,
4.2
,
2
,
2
,
54
,
21
,
4
,
2
)
Calculate the total
result.
sum
<-
sum
(
x
)
(
result.
sum
)
The output of the code above is:
[1] 85.2
When a vector contains missing values NA, if na.rm = TRUE is not set, sum() returns NA:
Example
A vector containing NA
x
<-
c
(
10
,
20
, NA,
30
,
40
)
Without handling NA, the result is NA
result.
na
<-
sum
(
x
)
(
result.
na
)
Set na.rm = TRUE to ignore NA
result.
ok
<-
sum
(
x, na.
rm
=
TRUE
)
(
result.
ok
)
The output of the code above is:
[1] NA
[1] 100
R Language Examples