Dear R-Gurus,
I needed to create in R a function similar to build-in acf() (= Auto Correlation Function).
First I looked at the source of of build-in acf() using the command
Then I created my function named my_acf() with almost same result structure as the original acf() has, i.e.:
But I had no luck with that:
Although the original function acf() returns on this vector
the nice output
my function my_acf() returned this ugly output
Then I noticed that I don't have the class="acf" attribute in my function result.
I added it and now it's OK:
Now the output of my function my_acf() matches the output of the built-in acf() function.
But still, I don't understand how R knows that it should make a special output for the class "acf".
Where and how is it coded?
I needed to create in R a function similar to build-in acf() (= Auto Correlation Function).
First I looked at the source of of build-in acf() using the command
Code:
getAnywhere(plot.acf)
Code:
> str(my_acf(x))
List of 6
$ acf : num [1:4, 1, 1] 1 0.25 -0.3 -0.45
$ type : chr "correlation"
$ n.used: int 4
$ lag : num [1:4, 1, 1] 0 1 2 3
$ series: chr "x"
$ snames: NULL
> str(acf(x))
List of 6
$ acf : num [1:4, 1, 1] 1 0.25 -0.3 -0.45
$ type : chr "correlation"
$ n.used: int 4
$ lag : num [1:4, 1, 1] 0 1 2 3
$ series: chr "x"
$ snames: NULL
- attr(*, "class")= chr "acf"
Although the original function acf() returns on this vector
Code:
> x <- c(1, 2, 3, 4)
Code:
> y <- acf(x)
> y
Autocorrelations of series ‘x’, by lag
0 1 2 3
1.00 0.25 -0.30 -0.45
my function my_acf() returned this ugly output
Code:
> y <- my_acf(x)
> y
$acf
, , 1
[,1]
[1,] 1.00
[2,] 0.25
[3,] -0.30
[4,] -0.45
$type
[1] "correlation"
$n.used
[1] 4
$lag
, , 1
[,1]
[1,] 0
[2,] 1
[3,] 2
[4,] 3
$series
[1] "x"
$snames
NULL
I added it and now it's OK:
Code:
> y <- my_acf(x)
> y
Autocorrelations of series ‘x’, by lag
0 1 2 3
1.00 0.25 -0.30 -0.45
> y <- acf(x)
> y
Autocorrelations of series ‘x’, by lag
0 1 2 3
1.00 0.25 -0.30 -0.45
But still, I don't understand how R knows that it should make a special output for the class "acf".
Where and how is it coded?