The sum() function used to calculate sum of a numeric vector, list or data frame.

The following method shows how you can do it with syntax.

Method 1: Use sum() Function

sum(vector.na.rm=TRUE)


The following example shows how to use sum() function in R.

## Use sum() Function to Sum Values in Vector

Let’s see how we can calculate sum of values in vector:

# Define vector
vector1 <-c(20,25,27,29,30,32,39,40)

# Find sum of vector values
sum(vector1)


Output:

[1] 242


As the output shows addition of all elements of vector.

## Use sum() Function to Sum Values in Vector with Null Values

Suppose vector having null values in it then how we can calculate sum of values in vector:

# Define vector
vector1 <-c(20,NA,27,29,30,NA,39,NA)

# Find sum of vector values
sum(vector1,na.rm=TRUE)


Output:

[1] 145


The output shows the sum of all values in vector. It will avoid or remove null values while calculating sum.

## Use sum() Function to Find Sum of Values of Variable

You can use sum() function to calculate the sum of variable of dataframe:

# Create dataframe
df <- data.frame(Machine_name=c("A","B","C","D","A","A","G","B"),
Temperature=c(12,9,14,13,18,28,22,23),
Pressure=c(20,25,27,29,30,32,39,40))

# Find sum of values of Temperature column of dataframe
sum(df\$Temperature)


Output:

[1] 139


Here the output shows sum of values of Temperature column of dataframe.

## Use sum() Function to Find of Sum of Values of Multiple Variables

You can apply sum() function on multiple variables of dataframe to calculate sum of values:

# Create dataframe
df <- data.frame(Machine_name=c("A","B","C","D","A","A","G","B"),
Temperature=c(12,9,14,13,18,28,22,23),
Pressure=c(20,25,27,29,30,32,39,40))

# Find sum of values of Temperature,Pressure columns of dataframe
sapply(df[ , c('Temperature', 'Pressure')], sum)


Output:

Temperature    Pressure
139         242


The output shows sum of values for Temperature and Pressure column respectively.

Note that you can apply sum() function on numeric dataset to calculate sum.