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

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

Интервал:

Закладка:

Сделать

The variable a does not appear in the scope of the functions.

However, a function can access a variable defined the level higher if it is not re-defined in the function itself (see what happens with the variable c: it is not defined in g(), so automatically R will search the environment above.

The function g() can use the variable b without defining it or without it being passed as an argument. When it changes that variable, it can use that new value, but once we are back in the function f(), the old value is still there.

5.2 Lexical Scoping in R

Just as any programming language, R as rules for lexical scoping. R is extremely flexible and this can be quite intimidating when starting, but it is possible to amass this flexibility.

First, a variable does not necessarily need to be declared,R will silently create it or even change it is type.

x <-‘Philippe’ rm(x) # make sure the definition is removed x # x is indeed not there (generates an error message) ## Error in eval(expr, envir, enclos): object ‘x’ not foundx <- 2L # now x is created as a long integer x <- pi # coerced to double (real) x <- c(LETTERS[1 :5]) # now it is a vector of strings

This can, of course, lead to mistakes in our code: we do not have to declare variables, so we cannot group those declarations so that these error become obvious. This means that if there is a mistake, one might expect to see strange results that are hard to explain. In such case, debugging is not easy. However, this is quite unlikely to come into your way. Follow the rule that one function is never longer than half an A4 page and most likely this feature of R will save time instead of increasing debugging time.

Next, one will expect that each variable has a scope.

# f # Demonstrates the scope of variablesf <- function() { a <-pi # define local variable print(a) # print the local variable print(b) # b is not in the scope of the function} # Define two variables a and ba <-1 b <-2 # Run the function and note that it knows both a and b. # For b it cannot find a local definition and hence # uses the definition of the higher level of scope. f() ## [1] 3.141593 ## [1] 2 # f() did not change the value of a in the environment that called f(): print(a) ## [1] 1

This illustrates that the scoping model in R is dynamical scoping . This means that when a variable is used, that R in the first place will try to find it in the local scope, if that fails, it goes a step up and continues to do so until R ends up at the root level or finds a definition.

dynamical scoping

картинка 65Note – Dynamic scoping

Dynamic scoping is possible, because R is an interpreted language. If R would be compiled, then the compiler would have a hard time to create all possible memory allocations at the time of compilation.

To take this a step further we will study how the scoping within S3 objects works. 1 The example below is provided by the R Core Team.

# Citation from the R documentation: # Copyright (C) 1997-8 The R Core Teamopen.account <- function(total) { list( deposit = function(amount) { if(amount <=) stop(“Deposits must be positive!\n”) total <<-total +amount cat(amount,“deposited. Your balance is”, total, “\n\n”) }, withdraw = function(amount) { if(amount >total) stop(“You do not have that much money!\n”) total <<-total -amount cat(amount,“withdrawn. Your balance is”, total, “\n\n”) }, balance = function() { cat(“Your balance is”, total, “\n\n”) } ) } ross <- open.account(100) robert <- open.account(200) ross $withdraw(30) ## 30 withdrawn. Your balance is 70 ross $balance() ## Your balance is 70 robert $balance() ## Your balance is 200 ross $deposit(50) ## 50 deposited. Your balance is 120 ross $balance() ## Your balance is 120 try(ross $withdraw(500)) # no way..## Error in ross$withdraw(500) : You do not have that much money!

This is a prime example of how flexible R is. At first this is quite bizarre, until we notice the <<-operator. This operator indicates that the definition of a level higher is to be used. Also the variable passed to the function automatically becomes an attribute of the object. Or maybe it was there because the object is actually defined as a function itself and that function got the parameter “amount” as a variable.

This example is best understood by realizing that this can also be written with a declared value “total” at the top level of our object.

картинка 66Warning – Dynamical scoping

While dynamical scoping has its advantages when working interactively, it makes code more confusing, and harder to read and maintain. It is best to be very clear with what is intended (if an object has an attribute, then declare it).Also never use variables of a higher level, rather pass them to your function as a parameter, then it is clear what is intended.)

In fact, a lot is going on in this short example and especially in the line total <<- total + amount. First, of all, open.accountis defined as a function. That function has only one line of code in some sense. This is a fortiori the last line of code, and hence, this is what the function will return. So it will try to return a list of three functions: “deposit,” “withdraw” and “balance.”

What might be confusing in the way this example is constructed is probably is that when the function open.account is invoked, it will immediately execute the first function of that list. Well, that is not what happens. What happens is that the open.accountobject gets a variable total, because it is passed as an argument. So, it will exist within the scope of that function.

The odd thing is that rather than behaving as a function this construct behaves like a normal object that has an attribute amountand a creator function open.account(). This function in sets this attribute to be equal to the value passed to that function.

картинка 67Hint –Write readable code

R will store variable definitions in its memory, and it may happen that you manage to read in a file for example, but then keep a mistake in your file. If you do not notice the mistake, it will go unnoticed (since your values are still there and you can work with them). The next person who tries to reproduce your code will fail. Start each file that contains your code with:

rm(list= ls()) # clear the environment

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

Интервал:

Закладка:

Сделать

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

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


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

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

x