How to Compute the Mean of a Data Frame Variable in R (2 Examples)
In this post you’ll learn how to compute the average of a variable in the R programming language.
Creation of Example Data
data(iris) # Loading iris data frame head(iris) # 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 |
data(iris) # Loading iris data frame head(iris) # 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
Example 1: Computing Mean of Column with $-Operator
mean(iris$Petal.Width) # Using mean function and $-operator # 1.199333 |
mean(iris$Petal.Width) # Using mean function and $-operator # 1.199333
Example 2: Computing Mean of Column that Contains Missing Values
iris$Petal.Width[c(5, 9, 20)] <- NA # Insert missing data |
iris$Petal.Width[c(5, 9, 20)] <- NA # Insert missing data
mean(iris$Petal.Width, na.rm = TRUE) # Using mean function and na.rm argument # 1.219048 |
mean(iris$Petal.Width, na.rm = TRUE) # Using mean function and na.rm argument # 1.219048
Further Resources & Related Tutorials
Have a look at the following R tutorials. They illustrate topics such as indices, data conversion, numeric values, and naming data.