rtidyversescalenormalizationrescale

rescale the selective range into 0 - 1?


I have a data frame like this:

df <- data.frame(FC=c(1, 2, 4, 2, 1, -4, -2))

And I'm trying to rescale the positive values between 0-1 and negative values also between 0- -1 so the output would be:

 FC
0.25
 0.5
   1
 0.5
0.25
  -1
-0.5

I have tried "scales" package in r

df$FC <- rescale(df$FC, to = c(0, 1))

But it is rescaling all values between 0-1.

How can I normalize columns by their individual range?

I really appreciate any help you can provide.


Solution

  • Here is a base R option

    transform(
        df,
        FC_scaled = FC / abs(ifelse(FC > 0, max(FC), min(FC)))
    )
    

    which gives

      FC FC_scaled
    1  1      0.25
    2  2      0.50
    3  4      1.00
    4  2      0.50
    5  1      0.25
    6 -4     -1.00
    7 -2     -0.50