Jie
Jie

Reputation: 43

Why do I get NAs from the following for loop?

I am trying to write a for loop to normalize the vector x with 5 values. However, after running the following code, I get the first four values as NAs and the last value as expected. Can anyone point out what the problem is? Thank you in advance!

x <- c(8.58, 10.46, 9.01, 9.64, 8.86)
x_mean <- mean(x)
x_sd <- sd(x)
n_x <- numeric()
for(i in length(x)){
   n_x[i] <- x[i] - x_mean / x_sd 
}
print(n_x)

Upvotes: 0

Views: 65

Answers (2)

Pedro Fonseca
Pedro Fonseca

Reputation: 331

You just need to replace replace length with seq_along:

x <- c(8.58, 10.46, 9.01, 9.64, 8.86)
x_mean <- mean(x)
x_sd <- sd(x)
n_x <- numeric()
for(i in seq_along(x)){
  n_x[i] <- (x[i] - x_mean) / x_sd 
}

n_x
-0.9718658  1.5310215 -0.3993969  0.4393366 -0.5990954

Edit:

You also had missing parenthesis in x[i] - x_mean / x_sd

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

As suggested in comments you have couple of typos in your post. Your code should work if you correct them. Apart from that you could do this in a vectorised way without the need of for loop.

x <- c(8.58, 10.46, 9.01, 9.64, 8.86)
x_mean <- mean(x)
x_sd <- sd(x)
n_x <- (x - x_mean)/x_sd
n_x
#[1] -0.9718658  1.5310215 -0.3993969  0.4393366 -0.5990954

Upvotes: 1

Related Questions