[R] Using R to Compute Covariance

peter dalgaard pdalgd at gmail.com
Sat Jul 26 21:30:54 CEST 2014


The Details section of ?cov.wt tells you that its divisor is not (n-1) for the "unbiased" method. Or rather, it tells you what it does, and that that amounts to dividing by n-1 _if_ the weights are equal. 

(I never quite figured out under which sampling/weighting model this estimator is actually unbiased, but that is a different story.) 

-pd

On 26 Jul 2014, at 20:07 , Robert Sherry <rsherry8 at comcast.net> wrote:

> I have the following data set:
> x    y           p
> 1    1          1/2
> 2    2          1/4
> 3    9          1/4
> 
> In this case, p represents the probability of the values occurring. I
> compute the covariance of x and y by hand and come up with a value of 41/16.
> When computing the covariance, I am dividing by n (in this case 3) not n-1.
> 
> I now want to use R to find the covarinace. I understand that R will divided
> by n-1 not n.  Here are the commands that I issued:
> 
> x = c(1,2,3)
> y = c(1,2,9)
> df =dataframe(x,y)
> w1 = c(1/2,1/4,1/4)
> cov.wt(df, wt = w1 )
> 
> The last command returns:
> 
> $cov
>    x    y
> x 1.1  4.1
> y 4.1 17.9
> 
> $center
>   x    y
> 1.75 3.25
> 
> $n.obs
> [1] 3
> 
> $wt
> [1] 0.50 0.25 0.25
> 
> Therefore, I conclude that R is finding the covariance of x and y to be 4.1.
> However, I need to adjust that number by multiplying it by 2 and then
> dividing by 3. However, when I get that I still do not get 41/16.  What am I
> missing?
> 
> I thank the group in advance for their responses.
> 
> Bob
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list