Question

The Rescale01 function below maps/scales all items in a vector to a range from 0 to...

The Rescale01 function below maps/scales all items in a vector to a range from 0 to 1. (Also discussed in lecture slides).

Rescale01 <- function(x){

rng <- range(x,na.rm = TRUE)

(x-rng[1])/(rng[2] - rng[1])

}

The function doesn’t work when x contains +ve or –ve infinity (indicated in R as Inf and –Inf, respectively). For example, if x is

x <- c(-1,-5,3,5,-3,0,2,Inf,-Inf)

Rescale01(x) returns a vector containing

NaN NaN NaN NaN NaN NaN NaN NaN NaN

Rewrite the function Rescale01 so that -Inf is mapped to 0, and Inf is mapped to 1.

Hint:

  • to check item in a vector is Inf, use is.infinite(x) & (x>0)
  • to check item in a vector is -Inf, use is.infinite(x) & (x<0)
  • Within the function, first thing you need to do is replace all Inf by the maximum value in the vector (considering only the valid items), and replace all –Inf by the minimum value in the vector (considering only the valid items)
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Rescale01 <- function(x){
x[is.infinite(x) & (x>0)]=max(x[!is.infinite(x)])
x[is.infinite(x) & (x<0)]=min(x[!is.infinite(x)])
rng <- range(x,na.rm = TRUE)
(x-rng[1])/(rng[2] - rng[1])
}

: Rescale01 <- function(x){ x[is.infinite(x) & (x>0)]=max(x[!is.infinite(x)]) x[is.infinite(x) & (x<0)]=min(x[!is.infinite(x)

Add a comment
Know the answer?
Add Answer to:
The Rescale01 function below maps/scales all items in a vector to a range from 0 to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT