5

The acf function in R's stats library includes the line

.Call(C_acf, x, lag.max, type == "correlation")

but I can't find the file C_acf anywhere on my machine (nor at https://github.com/SurajGupta/r-source nor https://github.com/wch/r-source).

Applying the advice at these questions didn't help:

https://stats.stackexchange.com/questions/254227/manual-calculation-of-acf-of-a-time-series-in-r-close-but-not-quite

How to see the source code of R .Internal or .Primitive function?

The file doesn't appear to be anywhere where people say to look. How can I find C_acf?

sdg238
  • 213
  • 1
  • 4
  • 3
    [Line 143 here](https://github.com/SurajGupta/r-source/blob/a28e609e72ed7c47f6ddfbb86c85279a0750f0b7/src/library/stats/src/filter.c)? I think the `C_` is dropped, as it is for `pnorm` in Ben Bolker's [answer here on the question you link](https://stackoverflow.com/a/14035586/903061) – Gregor Thomas Feb 07 '18 at 21:33
  • Ah ha! But how did you know to look in the file filter.c? – sdg238 Feb 07 '18 at 21:54
  • I searched the github repository for "acf", in the languages sidebar on the left I filtered the results to C. There were 5 results, and upon inspection the first one was correct. – Gregor Thomas Feb 07 '18 at 21:57

1 Answers1

6

This method will help identify the source code of the compiled function which has class of CallRoutine or NativeSymbolInfo.

Find the namespace of the call routine

getAnywhere(C_acf)
# namespace:stats

Download your version of the base R, because stats is part of the base R.

download.file(url = "https://cran.r-project.org/src/base/R-3/R-3.0.0.tar.gz", destfile = "./R-3.0.0.tar.gz")
untar(tarfile = "./R-3.0.0.tar.gz", exdir = "./")

handle directory paths

old_dir <- getwd()
setwd("./R-3.0.0/src/library/stats/src/")

find the word acf in source files. You have to go through the list of results and identify the exact function. The easiest way is to look at the function name and its arguments.

myresults <- sapply( list.files("./"), function(x) grep("acf", readLines(x), value = TRUE))
myresults <- myresults[lengths(myresults) != 0]
myresults[2] 
# $filter.c
# [1] "acf0(double *x, int n, int ns, int nl, int correlation, double *acf)"
# [2] "\t\tacf[lag + d1*u + d2*v] = (nu > 0) ? sum/(nu + lag) : NA_REAL;"     
# [3] "\t    se[u] = sqrt(acf[0 + d1*u + d2*u]);"                            
# [4] "\t\tacf[0 + d1*u + d2*u] = 1.0;"                                       
# [5] "\t\t\tacf[lag + d1*u + d2*v] /= se[u]*se[v];"                           
# [6] "SEXP acf(SEXP x, SEXP lmax, SEXP sCor)"                              
# [7] "    acf0(REAL(x), nx, ns, lagmax, cor, REAL(ans));"  

reset old directory path

setwd(old_dir)

Reference:

Sathish
  • 12,453
  • 3
  • 41
  • 59