[R] Calculate variance/covariance with complex numbers

Charles C. Berry cberry at tajo.ucsd.edu
Sun Mar 28 19:17:56 CEST 2010


On Sun, 28 Mar 2010, Gang Chen wrote:

> Thanks a lot for the help, Ben Bolker and Chuck!
>
> Chuck, it seems your version needs a little modification. Instead of this:
>
>> xri <- matrix(rnorm(10000)+1i*rnorm(10000),nc=2)
>> crossprod(xri-colMeans(xri))/(nrow(xri)-1)
>
> it seems to me it should be this (maybe there is a more elegant
> modification than mine?):
>> crossprod(t(apply(xri, 1, '-', colMeans(xri))))/(nrow(xri)-1)
>
> Do you agree?


Argh! Sorry for the 'thinko' (like a 'typo', but a misapplication of the 
brain rather than the fingers)!


I'd use this:

crossprod( sweep( xri, 2, colMeans(xri), "-" ))/(nrow(xri)-1)

or

crossprod(xri - rep(colMeans(xri),each=nrow(xri)))/(nrow(xri)-1)

Chuck

>
> Gang
>
>
>
> On Sat, Mar 27, 2010 at 7:07 PM, Charles C. Berry <cberry at tajo.ucsd.edu> wrote:
>> On Sat, 27 Mar 2010, Gang Chen wrote:
>>
>>> Anybody knows what functions can be used to calculate
>>> variance/covariance with complex numbers? var and cov don't seem to
>>> work:
>>
>> How about?
>>
>>> xri <- matrix(rnorm(10000)+1i*rnorm(10000),nc=2)
>>> crossprod(xri-colMeans(xri))/(nrow(xri)-1)
>>
>> HTH,
>>
>> Chuck
>>
>>>
>>>> a
>>>
>>>                       1
>>> V1 0.00810014+0.00169366i
>>> V2 0.00813054+0.00158251i
>>> V3 0.00805489+0.00163295i
>>> V4 0.00809141+0.00159533i
>>> V5 0.00813976+0.00161850i
>>>
>>>> var(a)
>>>
>>>            1
>>> 1 1.141556e-09
>>> Warning message:
>>> In var(a) : imaginary parts discarded in coercion
>>>
>>>> cov(a)
>>>
>>>            1
>>> 1 1.141556e-09
>>> Warning message:
>>> In cov(a) : imaginary parts discarded in coercion
>>>
>>> Thanks in advance,
>>> Gang
>>>
>>> ______________________________________________
>>> 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.
>>>
>>
>> Charles C. Berry                            (858) 534-2098
>>                                            Dept of Family/Preventive
>> Medicine
>> E mailto:cberry at tajo.ucsd.edu               UC San Diego
>> http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901
>>
>>
>>
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list