Joram
Joram

Reputation: 159

Finding maximum value per row and normalizing to this value

Is there a way to normalize many rows of a data frame according to the maximum value per row, preferably in dplyr?

Iniris I want to find the maximum per row of the columns Sepal.length, Sepal.width, Petal.length and Petal.width. I then want to divide every value by this maximum to get a range from 0 to 1. I want to be able to give a range of columns across which to find the maximum, and preferably not have to call them by name.

Output goal:

> iris
Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
5.1          3.5         1.4          0.2            setosa

> iris.normalized
Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1            3.5/5.1     1.4/5.1      0.2/5.1        setosa

I tried using the max function to no avail. I'm glad for any help.

Upvotes: 1

Views: 187

Answers (1)

akrun
akrun

Reputation: 887128

Using base R, calculate the max value per row with pmax and then divide with the columns of interest for scaling

iris[1:4] <-  iris[1:4]/do.call(pmax, iris[1:4])

Upvotes: 2

Related Questions