Philippe J. S. De Brouwer - The Big R-Book

Здесь есть возможность читать онлайн «Philippe J. S. De Brouwer - The Big R-Book» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

The Big R-Book: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «The Big R-Book»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Introduces professionals and scientists to statistics and machine learning using the programming language R Written by and for practitioners, this book provides an overall introduction to R, focusing on tools and methods commonly used in data science, and placing emphasis on practice and business use. It covers a wide range of topics in a single volume, including big data, databases, statistical machine learning, data wrangling, data visualization, and the reporting of results. The topics covered are all important for someone with a science/math background that is looking to quickly learn several practical technologies to enter or transition to the growing field of data science. 
The Big R-Book for Professionals: From Data Science to Learning Machines and Reporting with R Provides a practical guide for non-experts with a focus on business users Contains a unique combination of topics including an introduction to R, machine learning, mathematical models, data wrangling, and reporting Uses a practical tone and integrates multiple topics in a coherent framework Demystifies the hype around machine learning and AI by enabling readers to understand the provided models and program them in R Shows readers how to visualize results in static and interactive reports Supplementary materials includes PDF slides based on the book’s content, as well as all the extracted R-code and is available to everyone on a Wiley Book Companion Site
is an excellent guide for science technology, engineering, or mathematics students who wish to make a successful transition from the academic world to the professional. It will also appeal to all young data scientists, quantitative analysts, and analytics professionals, as well as those who make mathematical models.

The Big R-Book — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «The Big R-Book», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

So in S3, it is not the object that has to know how a call to it has to be handled, but it is the generic function 5 that gets the call and has to dispatch it.

The way this works in R is by calling UseMethod()in the dispatching function. This creates a vector of function names, like

UseMethod()

paste0(“generic”, “.”, c(class(x), “default”))

and dispatches to the most specific handling function available. The default class is the last in the list and is the last resort: if R does not find a class specific method it will call the default action.

Beneath you can see this in action:

# probe # Dispatcher function # Arguments: # x -- account object # Returns # confirmation of object typeprobe <- function(x) UseMethod(“probe”) # probe.account # action for account object for dispatcher function probe() # Arguments: # x -- account object # Returns # confirmation of object “account”probe.account <- function(x) “This is a bank account” # probe.default # action if an incorrect object type is provided to probe() # Arguments: # x -- account object # Returns # error messageprobe.default <- function(x) “Sorry. Unknown class” probe( structure( list(), class = “account”)) ## [1] “This is a bank account” # No method for class ‘customer’, fallback to ‘account’ probe( structure( list(), class = c(“customer”, “account”))) ## [1] “This is a bank account” # No method for class ‘customer’, so falls back to default probe( structure( list(), class = “customer”)) ## [1] “Sorry. Unknown class” probe(df) # fallback to default for data.frame## [1] “Sorry. Unknown class” probe.account(df) # force R to use the account method## [1] “This is a bank account” my_curr_acc <- account(“Philippe”, 150) # real account probe(my_curr_acc) ## [1] “This is a bank account”

картинка 69Note – Avoid direct calls

As you can see from the above, methods are normal R functions with a specific name. So, you might be tempted to call them directly (e.g. call directly print.data.frame()when working with a data-frame) Actually, that is not such a good idea. This means that if, for example later you improve the dispatch method that this call will never see those improvements.

картинка 70Hint – Speed gain

However, you might find that in some cases, there is a significant performance gain when skipping the dispatch method …well, in that case you might consider to bypass the dispatching and add a remark in the code to watch this instance. a

6.2.4 Group Generic Functions

It is possible to implement methods for multiple generic functions with one function via the mechanism of group generics. Group generic methods can be defined for four pre-specified groups of functions in R: “Math,” “Ops,” “Summary” and “Complex.” 6

The four “group generics” and the functions they include are:

1 Group Math: Members of this group dispatch on x. Most members accept only one argument, except log, round and signif that accept one or two arguments, while trunc accepts one or more. Members of this group are:abs, sign, sqrt, floor, ceiling, trunc, round, signifexp, log, expm1, log1p, cos, sin, tan, cospi, sinpi, tanpi, acos, asin, atan cosh, sinh, tanh, acosh, asinh, atanhlgamma, gamma, digamma, trigammacumsum, cumprod, cummax, cummin

2 Group Ops: This group contains both binary and unary operators ( +, - and !): when a unary operator is encountered, the Ops method is called with one argument and e2 is missing. The classes of both arguments are considered in dispatching any member of this group. For each argument, its vector of classes is examined to see if there is a matching specific (preferred) or Ops method. If a method is found for just one argument or the same method is found for both, it is used. If different methods are found, there is a warning about incompatible methods: in that case or if no method is found for either argument, the internal method is used. If the members of this group are called as functions, any argument names are removed to ensure that positional matching is always used.+, -, *, /, ∧, \%\%, \%/\%&, |, !==, !=, <, <=, >=, >

3 Group Summary: Members of this group dispatch on the first argument supplied.all, anysum, prodmin, maxrange

4 Group complex: Members of this group dispatch on z.Arg, Conj, Im, Mod, Re

Of course, a method defined for an individual member of the group takes precedence over a method defined for the group as a whole, because it is more specific.

картинка 71Note – Distinguish groups and functions

Math, Ops, Summary, and Complexaren't functions themselves, but instead represent groups of functions. Also note that inside a group generic function a special variable .Genericprovides the actual generic function that is called.

If you have complex class hierarchies, it is sometimes useful to call the parent method . This parent method is the method that would have been called if the object-specific one does not exist. For example, if the object is savings_account, which is a child of accountthen calling the function with savings_accountwill return the method associated to accountif there is no specific method and it will call the specific method if it exists.

картинка 72Hint – Find what is the next method

More information can be found using ?NextMethod.

6.3. S4 Objects

The S4 system is very similar to the S3 system, but it adds a certain obligatory formalism. For example, it is necessary to define the class before using it. This adds some lines of code but the payoff is increased clarity.

In S4

1 classes have formal definitions that describe their data fields and inheritance structures (parent classes);

2 method dispatch is more flexible and can be based on multiple arguments to a generic function, not just one; and

3 there is a special operator, @, for extracting fields from an S4 object.

All the S4 related code is stored in the methods package.

картинка 73Hint – Loading the library methods

While the methodspackage is always available when running R interactively (like in RStudio or in the R terminal), it is not necessarily loaded when running R in batch mode. So, you might want to include an explicit library(methods)statement in your code when using S4.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «The Big R-Book»

Представляем Вашему вниманию похожие книги на «The Big R-Book» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «The Big R-Book»

Обсуждение, отзывы о книге «The Big R-Book» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x