In statistics, mean in R is defined as an ‘average’ value that you simply get once you add all the values and divide them by the entire number of values.

This tutorial is focused R language on finding the mean of the values using different methods.

Mean in R with an input vector

In this method, we will first create a vector which includes multiple values in it. Then with the help of mean in R, we can calculate the mean value of the values present in the vector.

#List with multiple values
x <- c(34,54,32,34,67,65,45,34)

#Returns the mean of the list
mean(x)
45.625

In the above code, we first created an inventory ‘x’ containing some values. Then, with the assistance of function mean(), we will find the mean of the values within the vector ‘x’.

Mean of the values in a dataset

Now, let’s import a dataset in R and we will try to find the mean of the values present in it.

We will be using iris dataset for this purpose, which is available by default in R.

#Imports the dataset
df<- datasets::iris
df
      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
7            4.6         3.4          1.4         0.3     setosa
8            5.0         3.4          1.5         0.2     setosa
9            4.4         2.9          1.4         0.2     setosa
10           4.9         3.1          1.5         0.1     setosa

Well, our data is ready now. Here we will make use of mean() function to get the mean of the values of each column in the dataset.

Let’s see how it works!!!

mean(df$Sepal.Length)
5.843333
mean(df$Sepal.Width)
3.057333
mean(df$Petal.Length)
 3.758
mean(df$Petal.Width)
 1.199333
mean(df$Species)
 NA
Warning message:
In mean.default(df$Species) :
  argument is not numeric or logical: returning NA

Perfect!!!

You can observe in the above outputs, we have found out the mean of the values of all the columns in the dataset.

But in the last line of code, we got an error. Did we were wrong anywhere?

No. Instead, the mean() function should only applicable on the numerical data and not categorical data.

Wrapping Up

R language is a be a great statistical analysis language. It offers a variety of functions for mathematical computations. during this tutorial, we’ve used mean() function to seek out the mean of given values. you’ll find the mean of values by creating an inventory of values, a dataset and a list or a vector as shown above also .

I hope you got some good understanding of finding the mean of values using different methods.

That’s all for now, Happy R!!!

More read: R documentation

Categorized in: