sdg238
sdg238

Reputation: 213

R source file for acf function

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?

Upvotes: 5

Views: 701

Answers (1)

Sathish
Sathish

Reputation: 12723

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:

Upvotes: 6

Related Questions