23
You can use the sum() function in R to find the sum of values in a vector.
This function uses the following basic syntax:
sum(x, na.rm=FALSE)
where:
- x: Name of the vector.
- na.rm: Whether to ignore NA values. Default is FALSE.
The following examples show how to use this function in practice.
Example 1: Sum Values in Vector
The following code shows how to sum the values in a vector:
#create vector
x #sum values in vector
sum(x)
[1] 43
If there happen to be NA values in the vector, you can use na.rm=TRUE to ignore the missing values when calculating the mean:
#create vector with some NA values x #sum values in vector sum(x, na.rm=TRUE) [1] 25
Example 2: Sum Values in Data Frame Column
The following code shows how to sum the values in a specific column of a data frame:
#create data frame df frame(var1=c(1, 3, 3, 4, 5), var2=c(7, 7, 8, 3, 2), var3=c(3, 3, 6, 6, 8), var4=c(1, 1, 2, 8, 9)) #view data frame df var1 var2 var3 var4 1 1 7 3 1 2 3 7 3 1 3 3 8 6 2 4 4 3 6 8 5 5 2 8 9 #sum values in 'var1' column sum(df$var1) [1] 16
Example 3: Sum Values in Several Data Frame Columns
The following code shows how to use the sapply() function to sum the values in several columns of a data frame:
#create data frame df frame(var1=c(1, 3, 3, 4, 5), var2=c(7, 7, 8, 3, 2), var3=c(3, 3, 6, 6, 8), var4=c(1, 1, 2, 8, 9)) #view data frame df var1 var2 var3 var4 1 1 7 3 1 2 3 7 3 1 3 3 8 6 2 4 4 3 6 8 5 5 2 8 9 #sum values in 'var1' and 'var3' columns sapply(df[ , c('var1', 'var3')], sum) var1 var3 16 26
Additional Resources
How to Perform a COUNTIF Function in R
How to Perform a SUMIF Function in R
How to Use rowSums() Function in R
How to Use colSums() Function in R