在 R 中手动计算方差 [英] Calculate Variance Manually in R
本文介绍了在 R 中手动计算方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要你的帮助.我需要在 R 中手动计算方差.我已经用这个代码实现了它,它对于缺失值和非数字数据类型不够健壮.
I need your help here. I need to calculate variance manually in R. I have achieved it with this codes, it is to not robust enough for missing values and non-numeric data types.
a= c(1,2,3,4,5)
k=mean(a,na.rm = T)
storage=a
for(i in 1:length(a)) {
storage[i]= ((i-k)^2)
}
storage =sum((storage)/(length(a)-1))
storage
当我有 a= c(1,2,3,4,5,c,NA) 时,我遇到了麻烦请问我将如何编辑代码?
I run into trouble when I have a= c(1,2,3,4,5,c,NA) Please how would I edit the code?
推荐答案
您正在使用 for 循环,但这确实是不必要的,您可以创建一个函数对其进行矢量化,作为第一步,通过转换为字符然后是数字向量类型(因为 c
是一个函数)...
You are using a for loop but that is really unnecessary, you can make a function to vectorise it which removes the NAs from the data as the first step, via conversion to character then numeric vector types (because c
is a function)...
# Create data
set.seed(1)
x1 <- sample(1:10, 5)
x2 <- c(x1, c, NA)
# Make the function
varFunc <- function(x){
# Convert to character then numeric (non numeric become NA) then remove NAs
x <- as.numeric(as.character(x))[!is.na(as.numeric(as.character(x)))]
# Return Variance
sum((x-mean(x))^2) / (length(x)-1)
}
# Use the function
varFunc(x1)
varFunc(x2)
# Sanity check
var(x1)
var(x2, na.rm = TRUE)
这篇关于在 R 中手动计算方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文