Palash Kumar
Palash Kumar

Reputation: 429

Checking 0 vector in R

What is wrong in this function? I need to return same vector as input, if all values are 0, else min-max normalized

normalize <- function(x) {
    if (all(x==0)) return x
    return((x-min(x))/(max(x)-min(x)))
}

Upvotes: 1

Views: 1134

Answers (1)

Hack-R
Hack-R

Reputation: 23231

I think your problem was just that you didn't use () in your return statement.

x <- as.numeric(c(0,0,1,0,0,1,100,0,0,1,-23))

normalizeX <- function(x) {
  if (all(x==0)) {
   return (x) 
  } else{
    m      <- min(x)
    ma     <- max(x)
    result <- ((x-m)/(ma-m))
    return (result)
  }
}

normalizeX(x)

[1] 0.1869919 0.1869919 0.1951220 0.1869919 0.1869919 0.1951220 1.0000000 0.1869919 0.1869919 0.1951220 0.0000000

x <- as.numeric(c(0,0,0)) 
normalizeX(x)
[1] 0 0 0

I added some other minor changes, like calling the function something that's not going to be masked by packages, and storing the intermediate values for easier debugging / analysis.

Upvotes: 1

Related Questions