Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What does mean the class attribute in structure() and how it works ?

Status
Not open for further replies.

mikrom

Programmer
Mar 27, 2002
2,985
SK
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
Code:
getAnywhere(plot.acf)
Then I created my function named my_acf() with almost same result structure as the original acf() has, i.e.:
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"
But I had no luck with that:
Although the original function acf() returns on this vector
Code:
> x <- c(1, 2, 3, 4)
the nice output
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
Then I noticed that I don't have the class="acf" attribute in my function result.
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
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?
 

Part and Inventory Search

Sponsor

Back
Top