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

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

Интервал:

Закладка:

Сделать

try()

tryCatch()

handler

# f1 # Dummy function that from which only the error throwing part0 # is shown.f1 <- function() { # Here goes the long code that might be doing something risky # (e.g. connecting to a database, uploading file, etc.) # and finally, if it goes wrong: stop(“Early exit from f1!”) # throw error} tryCatch( f1(), # the function to tryerror = function(e) { paste(“_ERROR_:”,e)}, warning = function(w) { paste(“_WARNING_:”,w)}, message = function(m) { paste(“_MESSSAGE_:”,m)}, finally=“Last command” # do at the end) ## [1] “_ERROR_: Error in f1(): Early exit from f1!\n”

As can be understood from the example above, the error handler should not be evaluated if f1 does not throw an error. That is why they use error handling. So the following will not work:

# f1 # Dummy function that from which only the error throwing part # is shown.f1 <- function() { # Here goes the long code that might be doing something risky # (e.g. connecting to a database, uploading file, etc.) # and finally, if it goes wrong: stop(“Early exit from f1!”) # something went wrong} %>% tryCatch( error = function(e) { paste(“_ERROR_:”,e)}, warning = function(w) { paste(“_WARNING_:”,w)}, message = function(m) { paste(“_MESSSAGE_:”,m)}, finally=“Last command” # do at the end) # Note that it fails in silence.

картинка 102Further information – Error catching

There is a lot more to error catching than meets the eye here. We recommend to read the documentation of the relevant functions carefully. Another good place to start is “Advanced R,” page 163, Wickham (2014).

Another issue when using the pipe operator %>%occurs when functions use explicitely the current environment. In those functions, one will have to be explicit which environment to use. More about environments and scoping can be found in Chapter 5on page 81.

7.3.4 Advanced Piping

7.3.4.1 The Dollar Pipe

Below we create random data that has a linear dependency and try to fit a linear model on that data. 12

# This will not work, because lm() is not designed for the pipe.lm1 <- tibble(“x” = runif(10)) %>% within(y <-2 *x +4 + rnorm(10, mean=0, sd=0.5)) %>% lm(y ~x) ## Error in as.data.frame.default(data): cannot coerce class ““formula”” to a data.frame

The aforementioned code fails. This is because R will not automatically add something like data = tand use the “t” as far as defined till the line before. The function lm()expects as first argument the formula, where the pipe command would put the data in the first argument. Therefore, magrittrprovides a special pipe operator that basically passes on the variables of the data frame of the line before, so that they can be addressed directly: the %$%.

# The Tidyverse only makes the %>% pipe available. So, to use the # special pipes, we need to load magrittr library(magrittr) ## ## Attaching package: ‘magrittr’ ## The following object is masked from ‘package:purrr’: ## ## set_names ## The following object is masked from ‘package:tidyr’: ## ## extract lm2 <- tibble(“x” = runif(10)) %>% within(y <-2 *x +4 + rnorm(10, mean=0,sd=0.5)) %$% lm(y ~x) summary(lm2) ## ## Call: ## lm(formula = y ~ x) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.6101 -0.3534 -0.1390 0.2685 0.8798 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 4.0770 0.3109 13.115 1.09e-06 *** ## x 2.2068 0.5308 4.158 0.00317 ** ## --- ## Signif. codes: ## 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## ## Residual standard error: 0.5171 on 8 degrees of freedom ## Multiple R-squared: 0.6836,Adjusted R-squared: 0.6441 ## F-statistic: 17.29 on 1 and 8 DF, p-value: 0.003174

This can be elaborated further:

coeff <- tibble(“x” = runif(10)) %>% within(y <-2 *x +4 + rnorm(10, mean=0,sd=0.5)) %$% lm(y ~x) %>%summary %>%coefficients coeff ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 4.131934 0.2077024 19.893534 4.248422e-08 ## x 1.743997 0.3390430 5.143882 8.809194e-04

картинка 103Note – Using functions without brackets

Note how we can omit the brackets for functions that do not take any argument.

7.3.4.2 The T-Pipe

This works nice, but now imagine that we want to keep “t” as the tibble, but still add some operations on it – for example plot it. In that case, there is the special %T>%“T-pipe” that will rather pass on the left side of the expression than the right side. The output of the code below is the plot in Figure 7.3on page 136.

Figure 73 A linear model fit on generated data to illustrate the piping - фото 104

Figure 7.3: A linear model fit on generated data to illustrate the piping command.

library(magrittr) t <- tibble(“x” = runif(100)) %>% within(y <-2 *x +4 + rnorm(10, mean=0, sd=0.5)) %T>% plot(col=“red”) # The function plot does not return anything # so we used the %T>% pipe.lm3 <-t %$% lm(y ~x) %T>% # pass on the linear modelsummary %T>% # further pass on the linear modelcoefficients tcoef <-lm3 %>%coefficients # we anyhow need the coefficients # Add the model (the solid line) to the previous plot: abline(a = tcoef[1], b=tcoef[2], col=“blue”, lwd=3)

7.3.4.3 The Assignment Pipe

This last variation of the pipe operator allows us to simplify the first line, by providing an assignment with a special piping operator.

x <- c(1,2,3) # The following line:x <-x %>%mean # is equivalent with the following:x %<>%mean # Show x:x ## [1] 2

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

Интервал:

Закладка:

Сделать

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

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


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

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

x