Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 187

6.1. Base Types

Оглавление

The base types are build upon the “structures” from the language C that underlies R.2 Knowing this inheritance, the possibilities and limitations of the base types should not be a mystery. A struct is basically a collection of variables that are gathered under one name. In our example (the bank account) it could hold the name of the account holder, the balance as a number, but not the balance as a function. The following works:

struct

# Define a string: acc <- “Philippe” # Force an attribute, balance, on it: acc$balance <- 100 ## Warning in acc$balance <- 100: Coercing LHS to a list # Inspect the result: acc ## [[1]] ## [1] “Philippe” ## ## $balance ## [1] 100

This means that the base type holds information on how the object is stored in memory (and hence how much bytes it occupies), what variables it has, etc. The base types are part of R's code and compiled, so it is only possible to create new ones by modifying R's source code and recompiling. When thinking about the base types, one readily recalls all the types that we studied in the previous sections such as integers, vectors, matrices are base types. However, there are more exotic ones such as environments, functions, calls.

Some conventions are not straightforward but deeply embedded in R and many people's code, some things might be somewhat surprising. Consider the following code:

# a function build in core R typeof(mean) ## [1] “closure” is.primitive(mean) ## [1] FALSE # user defined function are “closures: add1 <- function(x) {x+1} typeof(add1) ## [1] “closure” is.function(add1) ## [1] TRUE is.object(add1) ## [1] FALSE

is.primitive()

typeof()

is.function()

is.object()

As mentioned before, the mainstream OO implementation in R is a generic-function implementation. That means that functions that display different behaviour for different objects will dispatch the action to a more specialized function.3

The importance of these struct-based base type is that all other object types are built upon these: S3 objects are directly build on top of the base types, S4 objects use a special-purpose base type, and RC objects are a combination of S4 and environments (which is also a base type).

The Big R-Book

Подняться наверх