Get Group Max / Min & Add as New Variable to Data in R (2 Examples)

This tutorial shows how to compute the group minima and maxima and append the result as a new variable to a data frame in R.

Creation of Example Data

data(iris)                            # Loading example data
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: Calculating Maximum Value by Group & Append as a New Column

iris_new1 <- iris                     # Add group maxima as new column
iris_new1$SL_min <- ave(iris_new1$Sepal.Length,
                        iris_new1$Species,
                        FUN = max)
head(iris_new1)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species SL_min
# 1          5.1         3.5          1.4         0.2  setosa    5.8
# 2          4.9         3.0          1.4         0.2  setosa    5.8
# 3          4.7         3.2          1.3         0.2  setosa    5.8
# 4          4.6         3.1          1.5         0.2  setosa    5.8
# 5          5.0         3.6          1.4         0.2  setosa    5.8
# 6          5.4         3.9          1.7         0.4  setosa    5.8

Example 2: Calculating Minimum Value by Group & Append as a New Column

iris_new2 <- iris                     # Add group minima as new column
iris_new2$SL_max <- ave(iris_new2$Sepal.Length,
                        iris_new2$Species,
                        FUN = min)
head(iris_new2)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species SL_max
# 1          5.1         3.5          1.4         0.2  setosa    4.3
# 2          4.9         3.0          1.4         0.2  setosa    4.3
# 3          4.7         3.2          1.3         0.2  setosa    4.3
# 4          4.6         3.1          1.5         0.2  setosa    4.3
# 5          5.0         3.6          1.4         0.2  setosa    4.3
# 6          5.4         3.9          1.7         0.4  setosa    4.3

Related Tutorials & Further Resources

Have a look at the following list of R tutorials. They explain topics such as dplyr, loops, naming data, and groups.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top