How can i rescale every column in my data frame to a 0-100 scale? (in r)

0

Issue

i am trying to get all the colums of my data frame to be in the same scale..

right now i have something like this… where a is on a 0-1 scale b is on a 100 scale and c is on a 1-5 scale

a   b     c 
0   89   4 
1   93   3 
0   88   5

How would i get it to a 100scale like this…

a     b      c 
0     89     80 
100   93     60 
0     88     100 

i hope that is somewhat clear..
i have tried scale() but can not seem to get it to work.

Solution

Using scale, if dat is the name of your data frame:

## for one column
dat$a <- scale(dat$a, center = FALSE, scale = max(dat$a, na.rm = TRUE)/100)
## for every column of your data frame
dat <- data.frame(lapply(dat, function(x) scale(x, center = FALSE, scale = max(x, na.rm = TRUE)/100)))

For a simple case like this, you could also write your own function.

fn <- function(x) x * 100/max(x, na.rm = TRUE)
fn(c(0,1,0))
# [1]   0 100   0
## to one column
dat$a <- fn(dat$a)
## to all columns of your data frame
dat <- data.frame(lapply(dat, fn))

Answered By – Blue Magister

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More