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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

6.2.1 Creating S3 Objects

S3 is a minimalistic and informal OO system; there is not even a formal definition of a class. In S3, you never create a class definition and start from the instance itself. Actually, to create an S3 object, it is sufficient to set its class attribute.

S3

my_curr_acc <- list(“name” = “Philippe”, “balance” <-100) class(my_curr_acc) <-“account” # set the class attribute otype(my_curr_acc) # it is an S3 object## [1] “S3” class(my_curr_acc) # the class type is defined above## [1] “account” # Note that the class attribute is not visible in the structure: str(my_curr_acc) ## List of 2 ## $ name: chr “Philippe” ## $ : num 100 ## - attr(*, “class”)= chr “account”

It is also possible to create a class and set the attribute simultaneously with the function structure.

structure()

my_object <- structure( list(), class = “boringClass”)

To create methods for S3 generic function, all we have to do is follow the syntax: <>.<>. R will then make sure that if an object of “class name” calls the generic function that then the generic function will dispatch the action to this specific function.

generic function

# print.account # Print an object of type ‘account’ # Arguments: # x -- an object of type accountprint.account <- function(x){ print( paste(“account holder”,x[[1]],sep=”: “)) print( paste(“balance “ ,x[[2]],sep=”: “)) } print(my_curr_acc) ## [1] “account holder: Philippe” ## [1] “balance : 100”

S3 objects are always build on other more elementary types. The function inherits (x, “classname”)allows the user to determine if the class x inherits from the class “classname.”

You probably remember that R returned “internal” “generic”as the class for some functions; so the class can be a vector. That means that the behaviour of that object can depend on different class-specific methods. The classes have to be listed from from most to least specific, so that the behaviour can follow this cascade and will always execute the most specific behaviour if it is present.

For example, the class of the glm()object is c(“glm”, “lm”). This means that the most specific class is the generalised linear model, but that some behaviour they might inherit from linear models. When a generic function will be called, it will first try to find a glm-specific method. If that fails, it will look for the lm-method.

It is possible to provide a constructor function for an S3 class. This constructor function can, for example be used to check if we use the right data-type for its attributes.

constructor

# account # Constructor function for an object of type account # Arguments: # x -- character (the name of the account holder) # y -- numeric (the initial balance of the account # Returns: # Error message in console in case of failure.account <- function(x,y) { if( !is.numeric(y)) stop(“Balance must be numeric!”) if( !is.atomic(x)) stop(“Name must be atomic!!”) if( !is.character(x)) stop(“Name must be a string!”) structure( list(“name” = x, “balance” = y), class = “account”) } # create a new instance for Paul:paul_account <- account(“Paul”, 200) # print the object with print.account():paul_account ## [1] “account holder: Paul” ## [1] “balance : 200”

The advantage of using the creator function for an instance of an object is obvious: it will perform some checks and will avoid problems later on. Unlike in message-passing OO implementations, the S3 implementation allows to bypass the creator function or worse it allows you to change the class all too easy. Consider the following example.

creator function

class(paul_account) <-“data.frame” print(paul_account) # R thinks now it is a data.frame## [1] name balance ## <0 rows> (or 0-length row.names) paul_account[[2]] # the data is still correct## [1] 200 class(paul_account) <-“account” print(paul_account) # back to normal: the class is just an attribute## [1] “account holder: Paul” ## [1] “balance : 200”

6.2.2 Creating Generic Methods

We already saw how to create a method for a generic function by using simply the right naming convention. To add a new generic function, it is sufficient to call UseMethod().

UseMethod()

UseMethod() takes two arguments: the name of the generic function, and the argument to use for the method dispatch. If you omit the second argument it will dispatch on the first argument to the function. There is no need to pass any of the arguments of the generic to UseMethod(), R will take care of that for you.

# add_balance # Dispatcher function to handle the action of adding a given amount # to the balance of an account object. # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balanceadd_balance <- function(x, amount) UseMethod(“add_balance”)

This construct will do nothing else than trying to dispatch the real action to other functions. However, since we did not program them yet, there is nothing to dispatch to. To add those methods, it is sufficient to create a function that has the right naming convention.

# add_balance.account # Object specific function for an account for the dispatcher # function add_balance() # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balanceadd_balance.account <- function(x, amount) { x[[2]] <-x[[2]] +amount; # Note that much more testing and logic can go here # It is not so easy to pass a pointer to a function so we # return the new balance:x[[2]]} my_curr_acc <- add_balance(my_curr_acc, 225) print(my_curr_acc) ## [1] 325

Leaving the code up to this level is not really safe. It is wise to foresee a default action in case the function add_balance()is called with an object of another class.

# add_balance.default # The default action for the dispatcher function add_balance # Arguments: # x -- account -- the account object # amount -- numeric -- the amount to add to the balanceadd_balance.default <- function(x, amount) { stop(“Object provided not of type account.”) }

6.2.3 Method Dispatch

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

Интервал:

Закладка:

Сделать

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

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


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

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

x