How can I scale each column in my data frame to a scale of 0-100? (in g)

I am trying to get all the columns of my data frame at the same scale.

right now I have something like this ... where a is on a scale of 0-1 b on a scale of 100 and c is on a scale of 1-5

abc 0 89 4 1 93 3 0 88 5 

How can I get it in 100scale like this ...

 abc 0 89 80 100 93 60 0 88 100 

Hope this is somewhat clear. I tried scale () but cannot make it work.

+6
source share
2 answers

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 can 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)) 
+14
source

My experience is that this still goes unanswered, that if there is -2 in one of the columns, the current answer will not produce a 0-100 scale. Although I appreciate the answer when I tried to do this, do I have variables that are from -100 to 100, and this still left some kind of negative result?

I have a solution in case this applies to you:

 rescale <- function(x) (x-min(x))/(max(x) - min(x)) * 100 dat <- rescale(dat) 
0
source

Source: https://habr.com/ru/post/956301/


All Articles