Dmytro Fedoriuk
Dmytro Fedoriuk

Reputation: 351

What the difference between $ and attr( , var) in objects of R?

After calling attributes() function in R I get following results

$dim
[1] 10  1

$index
 [1] 1532869958 1532870058 1532870158 1532870258 1532870358 1532870458
 [7] 1532870558 1532870658 1532870758 1532870858
attr(,"tzone")
              TZ 
"Asia/Hong_Kong" 
attr(,"tclass")
[1] "POSIXct" "POSIXt" 

$class
[1] "xts" "zoo"

$.indexCLASS
[1] "POSIXct" "POSIXt" 

$tclass
[1] "POSIXct" "POSIXt" 

What the difference between $ and attr()? It seems like e.g. attr(,"tzone") returns same attribute that lies below. Why it duplicated?

Upvotes: 1

Views: 326

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47340

$ is a way to access an element from a list, attributes are not list elements.

The character $ is also used when printing a list to display element names.

The output of attributes is a list, that's why you see these $

str(attributes(iris))
# List of 3
# $ names    : chr [1:5] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" ...
# $ class    : chr "data.frame"
# $ row.names: int [1:150] 1 2 3 4 5 6 7 8 9 10 ...

Upvotes: 2

Related Questions