2个向量的样本协方差

Bil*_*ill 3 r

我正在尝试计算这两个向量之间的样本协方差.我用两个输入变量定义了一个函数.我不知道它是否正确?我的样本协方差公式也不会运行.任何人都可以帮我把它写在R?

  xv = c(1., 5.5, 7.8, 4.2, -2.7, -5.4, 8.9)
  yv = c(0.1, 1.5, 0.8, -4.2, 2.7, -9.4, -1.9)
  sampleCov= function(x,y){ 
    cov(xv,yv) = frac{sum_{i=1}^{n}(x_i-\mu_x)(y_i-\mu_y)}{n-1}].
    return (Cov(xv,yv)
  }
Run Code Online (Sandbox Code Playgroud)

Jil*_*ina 6

R 中有一个基本函数被调用cov,它完全符合您的要求,但是如果您想编写一个函数(不需要这样做),您可以尝试以下操作:

COV<- function(x,y) {
  if(length(x)!=length(y)) {stop('x must have the same length as y ')}
  x.bar <- mean(x)
  y.bar <- mean(y)
  N <- length(x)

  Cov <- (sum((x-x.bar)*(y-y.bar))) / (N-1)
  return(Cov)
}

COV(xv, yv)
[1] 8.697381

cov(xv, yv)
[1] 8.697381
Run Code Online (Sandbox Code Playgroud)

如您所见COV,结果相同,cov因此您不必为此编写函数。

此外,您的函数体没有 R 语法,而是您编写了不同的 LaTex 语法。


Rei*_*son 5

只需使用内部cov()功能:

xv <- c(1., 5.5, 7.8, 4.2, -2.7, -5.4, 8.9)
yv <- c(0.1, 1.5, 0.8, -4.2, 2.7, -9.4, -1.9)
cov(xv, yv)

R> cov(xv, yv)
[1] 8.697381
Run Code Online (Sandbox Code Playgroud)

如果你真的想重新发明轮子:

sampleCov <- function(x,y){
    stopifnot(identical(length(x), length(y)))
    sum((x - mean(x)) * (y - mean(y))) / (length(x) - 1)
}

R> sampleCov(xv, yv)
[1] 8.697381
Run Code Online (Sandbox Code Playgroud)