Open In App

How to find the sum of column values of an R dataframe?

Last Updated : 30 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to find the sum of the column values of a dataframe in R with the use of sum() function.

Syntax:

sum(dataframe$column_name)

Creating a Dataframe

A dataframe can be created with the use of data.frame() function that is pre-defined in the R library. This function accepts the elements and the number of rows and columns that are required for the dataframe to be created.

Following is an R Program for the creation of dataframe:

R




# R Program to create a dataframe
  
# Creating a Data Frame
df<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)
print(df)


Output:

  row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8

Computing Sum of Column Values

R language provides an in-built function sum() to compute the mean of a dataframe. Following is an R program for the implementation of sum().

R




# Computing sum of column values
  
# Using sum() function
sum(df$row1)
sum(df$row2)


Output:

3
12

Example 2:

R




# R program to illustrate dataframe 
Roll_num = c(01, 02, 03)
Age = c(22, 25, 45)
Marks = c(70, 80, 90)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(Roll_num, Age, Marks) 
print(df)
  
# Computing Sum using sum() function
sum(df$Roll_num)
sum(df$Age)
sum(df$Marks)


Output:

6
92
240

Example 3:

R




# R program to illustrate dataframe 
ID = c(01, 02, 03)
Age = c(25, 30, 70)
Salary = c(70000, 85000, 40000)
    
# To create dataframe use data.frame command and 
# then pass each of the vectors  
# we have created as arguments 
# to the function data.frame() 
df = data.frame(ID, Age, Salary) 
  
# Computing total salary
cat("Total Salary =", sum(df$Salary))


Output:

195000


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads