Why is a class considered as a special case of a vector in R?

I am currently reading The practical programming with the R . The author wrote the following paragraph -

A class is a special case of an atomic vector. For example, a stamp matrix is ​​a special case of a double vector. Each element in the matrix is ​​still double, but the elements have been arranged in a new structure. R added a class attribute to die when you changed its dimensions. This class describes the new format. Many functions R will specifically look for an attribute of an object class, and then process the object in a predetermined manner based on the attribute.

From what I understand, this statement should not be, on the contrary. A vector is a special case of a matrix because its sizes are Nx1instead NxM. The similarity, should not be a vector, is a special case of the class, because the vector has a class NULL.

Why is this not so?

+4
source share
1 answer

That the author refers (in a certain sense imho) is an internal representation of objects. They all represent some type of “list” with additional bits of information that determine how R works with it.

Take, for example, the matrix. The matrix is ​​a vector with an additional attribute called "dim." It is this attribute that makes it the matrix. Removing the attribute shows the basic structure of the vector:

> x <- matrix(1:10, ncol = 5)
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

> attributes(x)
$dim
[1] 2 5

> attr(x,"dim") <- NULL
> x
 [1]  1  2  3  4  5  6  7  8  9 10

, , . S3, - . "class".

S3 - : , . , print(), summary() .., .

, . :

> class(iris)
[1] "data.frame"
> attributes(iris)
$names
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
$row.names
  [1]   1   2   3   4   5   ... 
$class
[1] "data.frame"
> class(iris) <- NULL
> class(iris)
[1] "list"

S3 "class". , , , "lm". .

S4, . S4 , , "" "". , , , S3. S4 , , , , , S4.

: R. : . , . , . , . " ", , , .

+3

Source: https://habr.com/ru/post/1687635/


All Articles