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

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

Интервал:

Закладка:

Сделать

Digression – The speed of loops

The code base of R has been improved a lot and loops are faster than they used to be, however, there can still be a significant time difference between using a loop or using a pre-implemented function.

n <-10 ∧7 v1 <-1 :n # -- using vector arithmetict0 <- Sys.time() v2 <-v1 *2 t1 <- Sys.time() -t0 print(t1) ## Time difference of 0.06459093 secs # -- using a for loop rm(v2) v2 <- c() t0 <- Sys.time() for(k inv1) v2[k] <-v1[k] *2 t2 <- Sys.time() -t0 print(t2) ## Time difference of 3.053826 secs # t1 and t2 are difftime objects and only differences # are defined. # To get the quotient, we need to coerce them to numeric.T_rel <- as.numeric(t2, units = “secs”) / as.numeric(t1, units = “secs”) T_rel ## [1] 47.27949

Note that in our simple experiment the for-loop is 47.3 times slower than the vector operation! So, use operators at the highest level (vectors, matrices, etc) and especially do an effort to understand the apply-family functions (see Chapter 4.3.5 “ Arrays ” on page 50) or their tidyverse equivalents: the map-family of functions of the package purrr. An example for the apply-family can be found in Chapter 22.2.6 on page 513 and one for the mapfamily is in Chapter 19.3 on page 459.

картинка 52Further information – Speed

Further information about optimising code for speed and more elegant and robust timing of code can be found in Chapter 40“ The Need for Speed ” on page 997.

4.6 Functions

More than in any other programming language, functions play a prominent role in R. Part of the reason is the implementation of the dispatcher function based object model with the S3 objects—see Chapter 6“ The Implementation of OO ” on page 117.

functions

The user is both able to use the built-in functions and/or define his own bespoke functions.

4.6.1 Built-in Functions

Right after starting, R some functions are available. We call these the “built-in functions.” Some examples are:

demo(): shows some of the capabilities of R

demo()

q(): quits R

q()

data(): shows the datasets available

data()

help(): shows help

help()

ls(): shows variables

ls()

c(): creates a vector

c()

seq(): creates a sequence

seq()

mean(): calculates the mean

mean()

max(): returns the maximum

max()

sum(): returns the sum

sum()

paste(): concatenates vector elements

paste()

4.6.2 Help with Functions

If you do not remember exactly what parameters a certain function needs or what type of variable the output will be, then there are multiple ways to get support in R.

apropos()

Help with functions

help(c) # shows help help with the function c ?c # same result apropos(“cov”) # fuzzy search for functions

картинка 53Further information on packages

R has many “packages” that act as a library of functions that can be loaded with one command. For more information refer to Chapter 4.7 “ Packages ” on page 96.

4.6.3 User-defined Functions

function()

The true flexibility comes from being able to define our own functions. To create a function in R, we will use the function-generator called “function.”

function – create

Function use for function()

In R a user defined function (UDF) is created via the function function().

function_name <- function(arg_1, arg_2, …) { function_body return_value }

Example: A bespoke function

# c_surface # Calculates the surface of a circle # Arguments: # radius -- numeric, the radius of the circle # Returns # the surface of the ciclec_surface <- function(radius) { x <-radius ∧2 *pi return(x) } c_surface(2) +2 ## [1] 14.56637

Note that it is not necessary to explicitly “return” something. A function will automatically return the last value that is send to the standard output. So, the following fragment would do exactly the same:

# c_surface # Calculates the surface of a circle # Arguments: # radius -- numeric, the radius of the circle # Returns # the surface of the ciclec_surface <- function(radius) { radius ∧2 *pi } # Test the function: c_surface(2) +2 ## [1] 14.56637

4.6.4 Changing Functions

Usually,we will keep functions in a separate file that is then loaded in our code with the command source(). Editing a function is then done by changing this file and reloading it – and hence overwriting the existing function content.

Most probably you will work in a modern environment such as the IDE RStudio,which makes editing a text-file with code and running that code a breeze. However, there might be cases where one has only terminal access to R. In that case, the following functions might come in handy.

edit()

fix()

# Edit the function with vi: fix(c_surface) # Or us edit:c_surface <- edit()

картинка 54Hint

The edit()function uses the vieditor when using the CLI on Linux. This editor is not so popular any more and you might not immediately know how to close it. To get out of it: press [esc], then type :qand press [enter].

vi

4.6.5 Creating Function with Default Arguments

Assigning a default value to the argument of a function means that this argument will get the default value, unless another value is supplied – in other words: if nothing is supplied then the default is used.

It is quite handy to have the possibility to assign a default value to a function. It allows to save a lot of typing work and makes code more readable, but it allows also to add a variable to an existing function and make it compatible with all previous code where that argument was not defined.

paste()

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

Интервал:

Закладка:

Сделать

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

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


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

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

x