Generally, if you have a vector x
and you want to linearly transform x
so its range is from r1
to r2
, you transform it like this:
result = (x - min(x)) / (max(x) - min(x)) * (r2 - r1) + r1
We could put this in a convenient function that handles NA
values nicely:
rescale = function(x, range) {
rx = range(x, na.rm = TRUE)
(x - rx[1]) / diff(rx) * diff(range) + range[1]
}
Which you could use like this:
rescale(1:4, range = c(1, 10))
# [1] 1 4 7 10
Or in your particular case, your_data$col1to4 = rescale(your_data$col1to4, range = range(your_data$col1to10))