我想计算样本中R的方差。你可以在下面找到我的代码。
我无法在此步骤中列出差异列表diff[length(diff)+1] <- spin_time[y] - mean
。有些事情是错的,我无法弄清楚。
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))
答案 0 :(得分:2)
你的代码唯一的问题是范围(1,x)在R中不起作用。相反,你需要使用c(1:length_spin_time)。
另外,你可以做矢量减法,向量乘法和东西加载。还有一个方差函数(var(array))。