Open In App

sum() function in R

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

sum() function in R Programming Language returns the addition of the values passed as arguments to the function.

Syntax: sum(…)

Parameters: 

  • …: numeric or complex or logical vectors

sum() Function in R Example

R program to add two numbers

Here we will use sum() functions to add two numbers.

R
a1=c(12,13)

sum(a1)

Output:

[1] 25

Sum() function with vector

Here we will use the sum() function with a vector, for this we will create a vector and then pass each vector into sum() methods as a parameter.

R
# R program to illustrate
# sum function

# Creating Vectors
x <- c(10, 20, 30, 40)
y <- c(1.8, 2.4, 3.9)
z <- c(0, -2, 4, -6)

# Calling the sum() function
sum(x)  
sum(y)
sum(z)
sum(x, y, z)

Output: 

[1] 100
[1] 8.1
[1] -4
[1] 104.1

Sum() function in a range

For this, we will pass the range in the sum() function.

R
# R program to illustrate
# sum function

# Calling the sum() function
sum(1:5) # Adding a range
sum(-1:-10)
sum(4:12)

Output: 

[1] 15
[1] -55
[1] 72

Sum() function with NA

Here we will create a vector with NA value and then add using sum() function.

R
x = c(1,2,-4,5,12,NA)

sum(x,na.rm=TRUE)

Output:

16

Sum() function with Single Dataframe Column.

R
data = data.frame(iris)
print(head(data))
sum(data$Sepal.Width)

Output:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

458.6

Sum() function with Multiple Dataframe Column.

R
data = data.frame(iris)
print(head(data))
sum(data$Sepal.Length,data$Sepal.Width,data$Petal.Length,data$Petal.Width)

Output:

 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

2078.7

Calculate the sum of values in a matrix.

R
# Create a 2x3 matrix of numeric values
m <- matrix(c(1, 2, 3, 4, 5, 6, 7), nrow = 2)

# Calculate the sum of values in the matrix
sum_m <- sum(m)

# Print the result
print(sum_m)

output :

[1] 29

Calculate the sum of values with group_by using dplyr.

R
library('dplyr')
data = data.frame(iris)
print(head(data))
summarise(group_by(data,data$Species),sum(data$Petal.Length))

Output:

1 setosa                             564.
2 versicolor 564.
3 virginica 564.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads