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

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

Интервал:

Закладка:

Сделать

картинка 89Note

Fields can also be supplied as a vector (we use a list in the example). Using a vector does not allow to specify a type. It looks as follows:

setRefClass(“account”, fields = c(“ref_number”, “holder”, “branch”, “opening_date”, “account_type” ) )

картинка 90Hint

It is possible to leave the input type undecided by not providing a type in the list environment. This could look like this:

setRefClass(“account”, fields = list(holder, # accepts all typesbranch, # accepts all typesopening_date = “Date” # dates only) )

Let us now explore this object that was returned by the function setRefClass().

isS4(account) ## [1] TRUE # account is S4 and it has a lot more than we have defined:account ## Generator for class “account”: ## ## Class fields: ## ## Name: ref_number holder branch ## Class: numeric character character ## ## Name: opening_date account_type ## Class: Date c haracter ## ## Class Methods: ## “field”, “trace”, “getRefClass”, “initFields”, ## “copy”, “callSuper”, “.objectPackage”, “export”, ## “untrace”, “getClass”, “show”, “usingMethods”, ## “.objectParent”, “import” ## ## Reference Superclasses: ## “envRefClass”

The object returned by setRefClass(or retrieved later by getRefClass) is called a generator object . This object automatically gets the following methods.

generator object

new to create instances of the class. Its arguments are the named arguments specifying initial values for the fields;

methods to add methods or modify existing;

help to get help about the methods;

fields to get a list of attributes (fields) of that class;

lock to lock the named fields so that their value can only be set once;

accessors sets up accessor-methods in form of getxxx and setxxx (where “xxx” is replaced by the field names).

Refclass objects are mutable, or in other words, they have reference semantics. To understand this, we shall create the current account class and the investment account class.

custBank <- setRefClass(“custBank”, fields = list(name = “character”, phone = “character” ) ) invAccount <- setRefClass(“invAccount”, fields = list(custodian = “custBank”), contains = c(“account”) # methods go here)

Let us now come back to the current account and define it while adding some methods (though as we will see later, it is possible to add them later too).

# Definition of RC object currentAccountcurrAccount <- setRefClass(“currentAccount”, fields = list(interest_rate = “numeric”, balance = “numeric”), contains = c(“account”), methods = list( credit = function(amnt) { balance <<-balance +amnt }, debet = function(amnt) { if(amnt <=balance) { balance <<-balance -amnt } else{ stop(“Not rich enough!”) } } ) ) # note how the class reports on itself:currAccount ## Generator for class “currentAccount”: ## ## Class fields: ## ## Name: ref_number holder branch ## Class: numeric character character ## ## Name: opening_date account_type interest_rate ## Class: Date character numeric ## ## Name: balance ## Class: numeric ## ## Class Methods: ## “debet”, “credit”, “import”, “.objectParent”, ## “usingMethods”, “show”, “getClass”, “untrace”, ## “export”, “.objectPackage”, “callSuper”, “copy”, ## “initFields”, “getRefClass”, “trace”, “field” ## ## Reference Superclasses: ## “account”, “envRefClass”

картинка 91Note – Assigning in the encapsulating environment

Notice that, the assignment operator within an object is the local assignment operator: <<-. The operator <<-will call the accessor functions if defined (via the object$accessors()function).

We can now create accounts and use the methods supplied.

ph_acc <-currAccount $new(ref_number = 321654987, holder = “Philippe”, branch = “LDN05”, opening_date = as.Date( Sys.Date()), account_type = “current”, interest_rate = 0.01, balance = )

Now, we can start using the money and withdrawing money.

ph_acc $balance # after creating balance is 0:## [1] 0 ph_acc $debet(200) # impossible (not enough balance) ## Error in ph_acc$debet(200): Not rich enough!ph_acc $credit(200) # add money to the accountph_acc $balance # the money arrived in our account## [1] 200 ph_acc $debet(100) # this is possibleph_acc $balance # the money is indeed gone## [1] 100

картинка 92Note – Addressing attributes and methods

The Reference Class OO implementation R5 uses the $to access attributes and methods.

It is also possible – though not recommendable – to create methods after creation of the class.

alsoCurrAccount <- setRefClass(“currentAccount”, fields = list( interest_rate = “numeric”, balance = “numeric”), contains = c(“account”) ) alsoCurrAccount $methods( list( credit = function(amnt) { balance <<-balance +amnt }, debet = function(amnt) { if(amnt <=balance) { balance <<-balance -amnt } else{ stop(“Not rich enough!”) } } ))

картинка 93Note – No dynamic editing of field definitions

In general, R is very flexible in how any of the OO systems is implemented. However, the refclasses do not allow to add fields after creating. This makes sense because it would make all existing objects invalid, since they would not have those new fields.

6.4.2 Important Methods and Attributes

All refclass object inherit from the same superclass envRefClass, and so they get at creation some hidden fields and methods. For example, there is .self. This variable refers to the object itself.

Other common methods for R5 objects that are always available (because they are inherited from envRefClass) are the following, illustrated for an object of RC class named RC_obj:

RC_obj$callSuper(): This method initializes the values defined in the super-class.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x