1

How can I see algorithm for cor() in R?

I'm not really an R user and the reason I ask is that I am converting some R code to Matlab.

The call I want to replicate is:

corr.data<=cor(xdata) 

where xdata is a n*m matrix where n is more than m.

So I need to know precisely how the calculation is done including any pre-processing of the data.

I have access to R and typed "cor" this gave the code for the function:

The relevant part seems to be (I'm assuming pearson is being used as this is the default) in the call above:

if (method == "pearson") .Internal(cor(x, y, na.method, FALSE))

This seems slightly circular to me in that cor seems to being called again? Or does the Internal before it mean that this is a different cor function?

If so how can I see it's algorithm?

Kind Regards

Baz

Bazman
  • 2,058
  • 9
  • 45
  • 65
  • 2
    Read [this FAQ](http://stackoverflow.com/q/19226816/1412059). – Roland Dec 04 '13 at 16:05
  • Alternately does anybody know off hand whether the cov() function in Matlab behaves the same as cov() in R? – Bazman Dec 04 '13 at 16:08
  • I believe [corrcoef](http://www.mathworks.de/de/help/matlab/ref/corrcoef.html) does the same as `cor` (with defaults). Should be easy to check (if you have Matlab installed). – Roland Dec 04 '13 at 16:10
  • 2
    I think you have an older version of R as mine has a call to `C_cor` which is found in [here](https://github.com/wch/r-source/blob/8be89707a140b0ba3ff0f96a438ff502c6abb91f/src/library/stats/src/cov.c#L636) – eddi Dec 04 '13 at 19:07

2 Answers2

1

You can only see .internal() looking at the source code of R. The code will be written in C.

Usobi
  • 1,816
  • 4
  • 18
  • 25
  • Is it realistic to try and read it without a strong background in C++? If not have these internal algorithms been documented anywhere else? – Bazman Dec 04 '13 at 16:06
  • 1
    I would suggest to trust in what the `help('cor')` says is true. Understanding almost any source code is quite hard. – Usobi Dec 04 '13 at 16:15
  • If you want to know how `cor` and `cov` are computed, look for examples across the web, like wikipedia. R `cov` does not result in the same result as Matlab `cov`? I have no idea about Matlab – Usobi Dec 04 '13 at 16:17
0

From ?cor : "method: a character string indicating which correlation coefficient (or covariance) is to be computed. One of "pearson" (default), "kendall", or "spearman", can be abbreviated."

So you might start by determining which of these standard forms you want, and finding out which Matlab supports.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73