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.
Output:
[1] 10
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
x <- c (10, 20, 30, 40)
y <- c (1.8, 2.4, 3.9)
z <- c (0, -2, 4, -6)
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
sum (1:5)
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
m <- matrix ( c (1, 2, 3, 4, 5, 6, 7), nrow = 2)
sum_m <- sum (m)
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Aug, 2023
Like Article
Save Article