Overtime4728
Overtime4728

Reputation: 144

Items not added properly to pre-allocated vector in r

I'm trying to add data to a pre-allocated list but it only works half the time.

x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(0.5,1,1.5,2,2.5,3,3.5,4,4.5,5)

x_num      <- rep(0,length(x))
y_num      <- rep(0,length(y))

for (i in x){
  x_diff <- i - mean(x)
  print(x_diff)
  x_num[i]  <- x_diff
}

[1] -4.5
[1] -3.5
[1] -2.5
[1] -1.5
[1] -0.5
[1] 0.5
[1] 1.5
[1] 2.5
[1] 3.5
[1] 4.5

> x_num
[1] -4.5 -3.5 -2.5 -1.5 -0.5  0.5  1.5  2.5  3.5  4.5

for (i in y){
  y_diff <- i - mean(y)
  print(y_diff)
  y_num[i]  <- y_diff
}

[1] -2.25
[1] -1.75
[1] -1.25
[1] -0.75
[1] -0.25
[1] 0.25
[1] 0.75
[1] 1.25
[1] 1.75
[1] 2.25

> y_num
[1] -1.25 -0.25  0.75  1.75  2.25  0.00  0.00  0.00  0.00  0.00

The correct values are calculated for x_diff and y_diff but only x_num is filled properly. Is there something I'm missing here?

Upvotes: 1

Views: 36

Answers (1)

jay.sf
jay.sf

Reputation: 72901

You want the element number so you may want to use seq_along and subset y[i]

for (i in seq_along(y)){
  y_diff <- y[i] - mean(y)
  print(y_diff)
  y_num[i]  <- y_diff
}
# [1] -2.25
# [1] -1.75
# [1] -1.25
# [1] -0.75
# [1] -0.25
# [1] 0.25
# [1] 0.75
# [1] 1.25
# [1] 1.75
# [1] 2.25


y_num
# [1] -2.25 -1.75 -1.25 -0.75 -0.25  0.25  0.75  1.25  1.75  2.25

However, R is vectorized, so you may just do

y - mean(y)
# [1] -2.25 -1.75 -1.25 -0.75 -0.25  0.25  0.75  1.25  1.75  2.25

Upvotes: 3

Related Questions