I have a data frame like this:
df <- data.frame(x1=c(1, 2, 3, 2, 1),
x2=c(1, 10, 5, 8, 3))
And I'm trying to normalize both variables between 0 and 1. So 2 in x1
would be 0.5 and 5 in x2
would also be 0.5.
I have tried using the following normalization function:
range01 <- function(x){(x-min(x, na.rm = T))/(max(x, na.rm = T)-min(x, na.rm = T))}
df <- range01(df)
But instead it normalizes all variables by range of the entire data frame (1 to 10), giving this:
x1 x2
0.0000000 0.0000000
0.1111111 1.0000000
0.2222222 0.4444444
0.1111111 0.7777778
0.0000000 0.2222222
How can I normalize both columns by their individual range? I need a systematic function to do this, since I am working with many variables across many data frames in a for loop.