How to find the sum of column values of an R dataframe?
Last Updated :
30 May, 2021
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
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
sum (df$row1)
sum (df$row2)
|
Output:
3
12
Example 2:
R
Roll_num = c (01, 02, 03)
Age = c (22, 25, 45)
Marks = c (70, 80, 90)
df = data.frame (Roll_num, Age, Marks)
print (df)
sum (df$Roll_num)
sum (df$Age)
sum (df$Marks)
|
Output:
6
92
240
Example 3:
R
ID = c (01, 02, 03)
Age = c (25, 30, 70)
Salary = c (70000, 85000, 40000)
df = data.frame (ID, Age, Salary)
cat ( "Total Salary =" , sum (df$Salary))
|
Output:
195000
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...