How to find the mean of all values in an R data frame?
In this article, we are going to find the mean of the values of a dataframe in R with the use of mean() function.
Syntax:
mean(dataframe)
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 Mean of the Dataframe
R language provides an in-built function mean() to compute the mean of a dataframe. Following is an R program for the implementation of mean().
R
mean1 = mean (df)
print (mean1)
|
Output:
Here in the above code, a warning message is displayed, which returns NA because the dataframe is not in a numeric form. There is a need to convert it into matrix form to compute the mean of the dataframe. R provides an inbuilt as.matrix() function to convert a dataframe to a matrix.
Output:
Now, to compute mean of this matrix created from a dataframe, use the mean function on the matrix.
Output:
4
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)
|
Output:
Output:
37.5555555555556
Example 3:
R
ID = c (01, 02, 03)
Age = c (25, 30, 70)
Salary = c (70000, 85000, 40000)
df = data.frame (ID, Age, Salary)
print (df)
|
Output:
Output:
21681.2222222222
Last Updated :
30 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...