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

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

Интервал:

Закладка:

Сделать

FALSE |NA ## [1] NA TRUE |NA ## [1] TRUE FALSE &NA ## [1] FALSE TRUE &NA ## [1] NA FALSE |NA |TRUE |TRUE ## [1] TRUE TRUE &NA &FALSE ## [1] FALSE

4.4.4 Assignment Operators

R has multiple ways to express an assignment. While it is possible to mix and match, we prefer to choose just one and stick with it. We will use <-.

operator – assignment

and

or

# left assignmentx <-3 x =3 x <<-3 # right assignment3 ->x 3 ->>x #chained assignmentx <-y <-4

not

The <<-or ->>operators change a variable in the actual environment and the environment above the actual one. Environments will be discussed in Section 5.1 “ Environments in R ” on page 110. Till now we have always been working in the command prompt. This is the root-environment. A function will create a new (subordinated) environment and might for example use a new variable. When the function stops running that environment stops to exist and the variable exists no longer. 3

assignment – left

assignment – right

assignment – chained

картинка 46Hint – Assignment

Generally it is best to keep it simple, most people will expect to see a left assignment, and while it might make code a little shorter, the right assignment will be a little confusing for most readers. Best is to stick to =or <-and of course <<-whenever assignment in a higher environment is also intended.

In some special cases, such as the definition of parameters of a function, it is not possible to use the “arrow” and onemust revert to the =sign. This makes sense, because that is not the same as a traditional assignment.

mean(v1, na.rm = TRUE) # works (v1 is defined in previous section)## [1] 1.75+0.375i mean(v1, na.rm <-TRUE) # fails ## Error in mean.default(v1, na.rm <- TRUE): ‘trim’ must be numeric of length one

While the <<-seems to do exactly the same, it changes also the value of the variable in the environment above the actual one. The following example makes clear how <-only changes the value of xwhile the function is active, but <<-also changes the value of the variable xin the environment where the function was called from.

# f # Assigns in the current and superior environment 10 to x, # then prints it, then makes it 0 only in the function environment # and prints it again. # arguments: # x -- numericf <- function(x) {x <<-10; print(x); x <-; print(x)} x <-3 x ## [1] 3 # Run the function f(): f(x) ## [1] 10 ## [1] 0 # Only the value assigned with <<- is available now:x ## [1] 10

Digression – For C++ programmers

If you are moving from C++, you will miss the speed and functionality of passing variable by their pointer. The <<-operator will provide you the ability to change a variable in the environment above the function.

картинка 47Warning – Sparingly change variables in other environments

While it is certainly cool and most probably efficient to change a variable in the environment above the function, it will make your code harder to read and if the function is hidden in a package it might lead to unexpected side effects. This superpower is best used sparingly.

4.4.5 Other Operators

There are of course more operators, that allow to execute common commands more efficiently or apply to certain specific objects such asmatrices. For example, we already have seen the operator :that creates a sequence. In R it is possible to define your own operators.

# +-+ # This function is a new operator # arguments: # x -- numeric # y -- numeric # returns: # x- y`+-+` <- function(x, y) x -y 5 +-+5 ## [1] 0 5 +-+1 ## [1] 4 # Remove the new operator: rm(`+-+`)

картинка 48Warning – Redefine existing operators

It is even possible to redefine elementary operators such as +with the aforementioned code. This is of course not a wise thing to do, but we understand how it can be a fun practical joke or a tricky job interview question.

The following are some common operators that help working with data.

operator – other

# create a listx <- c(10 :20) x ## [1] 10 11 12 13 14 15 16 17 18 19 20 # %in% can find an element in a vector2 %in%x # FALSE since 2 is not an element of x## [1] FALSE 11 %in%x # TRUE since 11 is in x## [1] TRUE x[x %in% c(12,13)] # selects elements from x## [1] 12 13 x[2 :4] # selects the elements with index## [1] 11 12 13 # between 2 and 4

4.5 Flow Control Statements

R is Turing complete and hence offers a range of tools to make choices and repeat certain parts of code. Knowing the different ways to change the flow of a code by if-statements and loops is essential knowledge for each R-programmer.

flow control

4.5.1 Choices

4.5.1.1 The if-Statement

The workhorse to control the flow of actions is the if()function.

if()

The construct is both simple and efficient.

Function use for if()

if(logical statement) { executed if logical statement is true } else { executed if the logical statement if false }

Note that the else-statement is optional.

This basic construct can also be enriched with else ifstatements. For example, we draw a random number from the normal distribution and check if it is bigger than zero.

set.seed(1890) x <- rnorm(1) if(x <0) { print(‘x is negative’) } else if(x >0) { print(‘x is positive’) } else{ print(‘x is zero’) } ## [1] “x is positive”

картинка 49Hint – Extending the if-statement

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

Интервал:

Закладка:

Сделать

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

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


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

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

x