[R] Using R to Compute Covariance
Robert Sherry
rsherry8 at comcast.net
Sat Jul 26 22:20:01 CEST 2014
David,
Thanks for the response. I believe you have solved my problem.
Bob
On 7/26/2014 3:50 PM, David Winsemius wrote:
>
> On Jul 26, 2014, at 11:07 AM, Robert Sherry 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 [covariance]. I understand that R
>> will [divide]
>> by n-1 not n.
>
> Please read what the help page says about the choice of the method
> parameter.
>
>
>> Here are the commands that I issued:
>>
>> x = c(1,2,3)
>> y = c(1,2,9)
>> df =dataframe(x,y)
>
> # There's no function named 'dataframe'.\\
>
>> df =data.frame(x,y)
>> w1 = c(1/2,1/4,1/4)
>> cov.wt(df, wt = w1 )
>>
>
> > cov.wt(df, wt = w1 ,method="ML")$cov[2,1]
> [1] 2.5625
> > all.equal (41/16, cov.wt(df, wt = w1 ,method="ML")$cov[2,1] )
> [1] TRUE
>
>
>> 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?
>
More information about the R-help
mailing list