Home > Enterprise >  Scale numbers based on the largest value
Scale numbers based on the largest value

Time:10-13

I have data like this:

mydata <- c(365673, 478934, 897464, 254778, 678899)

I want to transform mydata using unique number. This is how I calculate the unique number:

  • Extract the largest number, in this case, it is 897464
  • After that we get the unique number is 800000 from 897464
  • Then divide the vector with that value

The output that I want is going to be:

newdata <- mydata / 800000
newdata
# [1] 0.4570913 0.5986675 1.1218300 0.3184725 0.8486238

How do I create the function?

CodePudding user response:

I think this is what you are trying to do:

scale.nums <- function(v){
  x = max(v)
  pow <- 10^floor(log10(x))
  x <- x %/% pow * pow
  v/x
}

For example:

> mydata <- c(365673, 478934, 897464, 254778, 678899)
> scale.nums(mydata)
[1] 0.4570913 0.5986675 1.1218300 0.3184725 0.8486238

CodePudding user response:

plyr has round_any function which would be useful here.

mydata <- c(365673, 478934, 897464, 254778, 678899)

mydata/max(plyr::round_any(mydata, 100000, floor))
#[1] 0.4570913 0.5986675 1.1218300 0.3184725 0.8486238
  • Related