R sum() Function - Calculate Sum
The R sum() function is used to calculate the total sum of all elements in a vector or matrix.
When performing 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:
xInput vector, matrix, or column of a data frame.
na.rmBoolean value, defaults to FALSE, determines whether to remove missing values NA. Set to TRUE to ignore NA when calculating the sum.
Example
# Create vector
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate sum
result.sum <- sum(x)
print(result.sum)
x <- c(12, 27, 3, 4.2, 2, 2, 54, -21, 4, -2)
# Calculate sum
result.sum <- sum(x)
print(result.sum)
Executing the above code produces the following output:
[1] 85.2
When the vector contains missing values NA, if na.rm = TRUE is not set, sum() will return NA:
Example
# Vector containing NA
x <- c(10, 20, NA, 30, 40)
# Without handling NA, the result is NA
result.na <- sum(x)
print(result.na)
# Set na.rm = TRUE, ignore NA
result.ok <- sum(x, na.rm = TRUE)
print(result.ok)
x <- c(10, 20, NA, 30, 40)
# Without handling NA, the result is NA
result.na <- sum(x)
print(result.na)
# Set na.rm = TRUE, ignore NA
result.ok <- sum(x, na.rm = TRUE)
print(result.ok)
Executing the above code produces the following output:
[1] NA [1] 100Other Extensions
R Language Examples