Cem O.
Cem O.

Reputation: 3

Variance calculation in R - appending a vector

I would like to calculate variance in R for a sample. You can find my code below.

I cannot make a list of differences at this step, diff[length(diff)+1] <- spin_time[y] - mean . Something is wrong and I cannot figure it out.

spin_time <- c(4,5,6,7,8)

length_spin_time <- length(spin_time)

total <- 0

for (x in range(1, length_spin_time)){
    total <- total + spin_time[x]
}

mean <- total / length_spin_time

sum_diffsq <- 0
diff <- c()
diffsq <- c()


for (y in range(1, length_spin_time)){
  diff[length(diff)+1] <- spin_time[y] - mean
  diffsq[length(diffsq)+1] <- diff[y] * diff[y]
  sum_diffsq <- sum_diffsq + diffsq[y]
}

variance <- sum_diffsq / (length_spin_time - 1)

print(paste0("Variance is ",variance))

Upvotes: 0

Views: 231

Answers (1)

Gurpreet Singh
Gurpreet Singh

Reputation: 129

The only problem with your code is that range(1, x) does not work in R. Instead, you need to use c(1:length_spin_time).

Also, you can do vector subtraction, vector multiplication and loads of stuff. Also there is a function for variance (var(array)).

Upvotes: 2

Related Questions