[R] function doesn't change the variable in the right way

David Croll david.croll at gmx.ch
Fri Mar 7 12:17:26 CET 2014


Dear R users and friends,


I would like to ask you about the weird behaviour of a function I just 
wrote. This little function should take a vector, find NAs and 
substitute them for the mean of the vector, and return the normalized 
value of that vector.

I've tried both <- and <<- for changing the variables.

That's what I do:

# just a vector:
b <- c(1,1,1,NA,3,2)

# my function:
normalize <- function(x) {

     # copy x into new vector
     xn <- x

     # index of NAs
     nas <- which(is.na(xn) ==TRUE)
     m <- mean(xn, na.rm=TRUE)

     # insert mean for NAs
     xn[nas] <- m

     # normalize
     return((xn - mean(xn))/sd(xn))

}

# run...
normalize(b)

# here's what I get:
# [1] -0.75 -0.75 -0.75  0.00  1.75  0.50


The 4th value should be 1.6, but is 0.


I believe the answer to my problem is pretty obvious, but I can't see it...


Best regards,


David



More information about the R-help mailing list