Search code examples
rdataframenormalizing

How can I normalize column values in a data frame for all rows that share the same ID given in another column?


I have a dataframe that looks like this

ID  value
1   0.5
1   0.6
1   0.7
2   0.5
2   0.5
2   0.5

and I would like to add a column with normalization for values of the same ID like this: norm = value/max(values with same ID)

ID  value norm
1   0.5   0.5/0.7
1   0.6   0.6/0.7
1   0.7    1
2   0.5    1
2   0.3   0.3/0.5
2   0.5    1

Is there an easy way to do this in R without first sorting and then looping? Cheers


Solution

  • A solution using basic R tools:

    data$norm <- with(data, value / ave(value, ID, FUN = max))
    

    Function ave is pretty useful, and you may want to read ?ave.