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

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

Интервал:

Закладка:

Сделать

is.primitive()

typeof()

is.function()

is.object()

As mentioned before, the mainstream OO implementation in R is a generic-function implementation. That means that functions that display different behaviour for different objects will dispatch the action to a more specialized function. 3

The importance of these struct-based base type is that all other object types are built upon these: S3 objects are directly build on top of the base types, S4 objects use a special-purpose base type, and RC objects are a combination of S4 and environments (which is also a base type).

6.2. S3 Objects

S3 is probably the most simple implementation of an OO system that is still useful. In its simplicity, it is extremely versatile and user friendly (once you get your old C and C++ reflexes under control).

The function is.object()returns true both for S3 and S4 objects. There is no base function that allows directly to test if an object is S3, but there is a to test to check if an object is S4. So we can test if something is S3 as follows.

# is.S3 # Determines if an object is S3 # Arguments: # x -- an object # Returns: # boolean -- TRUE if x is S3, FALSE otherwiseis.S3 <- function(x){ is.object(x) & !isS4(x)} # Create two test objects:M <- matrix(1 :16, nrow=4) df <- data.frame(M) # Test our new function: is.S3(M) ## [1] FALSE is.S3(df) ## [1] TRUE

However, it is not really necessary to create such function by ourselves. We can leverage the library pryr, which provides a function otype()that returns the type of object.

pryr

otype()

library(pryr) otype(M) ## [1] “base” otype(df) ## [1] “S3” otype(df $X1) # a vector is not S3## [1] “base” df $fac <-factor(df $X4) otype(df $fac) # a factor is S3## [1] “S3”

The methods are provided by the generic function. 4 Those functions will do different things for different S3 objects.

If you would like to determine if a function is S3 generic, then you can check the source code for the use of the function useMethod(). This function will take care of the dispatching and hence decide which method to call for the given object.

useMethod()

However, this method is not foolproof because some primitive functions have this switch statement embedded in their C-code. For example, [, sum(), rbind(), and cbind()are generic functions, but this is not visible in their code in R.

Alternatively, it is possible to use the function ftypefrom the package pryr:

mean ## function (x, …) ## UseMethod(“mean”) ## ## ftype(mean) ## [1] “s3” “generic” sum ## function (…, na.rm = FALSE) .Primitive(“sum”) ftype(sum) ## [1] “primitive” “generic”

R calls the functions that have this switch in their C-code “internal” “generic”.

The S3 generic function basically decides to what other function to dispatch its task. For example, the function print can be called with any base or S3 object and print will decide what to do based on its class. Try the function apropos()to find out what different methods exist (or type print.in RStudio.

apropos(“print.”) ## [1] “print.AsIs” ## [2] “print.by” ## [3] “print.condition” ## [4] “print.connection” ## [5] “print.data.frame” ## [6] “print.Date” ## [7] “print.default” ## [8] “print.difftime” ## [9] “print.Dlist” ## [10] “print.DLLInfo” ## [11] “print.DLLInfoList” ## [12] “print.DLLRegisteredRoutines” ## [13] “print.eigen” ## [14] “print.factor” ## [15] “print.function” ## [16] “print.hexmode” ## [17] “print.libraryIQR” ## [18] “print.listof” ## [19] “print.NativeRoutineList” ## [20] “print.noquote” ## [21] “print.numeric_version” ## [22] “print.octmode” ## [23] “print.packageInfo” ## [24] “print.POSIXct” ## [25] “print.POSIXlt” ## [26] “print.proc_time” ## [27] “print.restart” ## [28] “print.rle” ## [29] “print.simple.list” ## [30] “print.srcfile” ## [31] “print.srcref” ## [32] “print.summary.table” ## [33] “print.summaryDefault” ## [34] “print.table” ## [35] “print.warnings” ## [36] “printCoefmat” ## [37] “sprintf” apropos(“mean.”) ## [1] “.colMeans” “.rowMeans” “colMeans” ## [4] “kmeans” “mean.Date” “mean.default” ## [7] “mean.difftime” “mean.POSIXct” “mean.POSIXlt” ## [10] “rowMeans”

This approach shows all functions that include “print.” in their name and are not necessarily the methods of the function print. Hence, amore elegant ways is to use the purpose build function methods().

methods()

methods(methods) ## no methods found methods(mean) ## [1] mean.Date mean.default mean.difftime ## [4] mean.POSIXct mean.POSIXlt ## see ‘?methods’ for accessing help and source code

картинка 68Hint – Naming conventions

Do not use the dot “.” in function names because it makes them look like S3 functional methods. This might lead to confusion with the convention that the methods are named as <>.<>. Especially, if there is more than one dot in the name. For example, print.data.frame()is not univocal: is it a dataframe method for the generic function print or is it the frame method for the generic function print.data? Another example is the existence of the function t.test()to run t-tests as well as t.dataframe(), that is the S3 method for the generic function t()to transpose a data frame.

t.test()

t.data.frame()

t()

To access the source code of the class-specific methods, one can use the function getS3method().

getS3method()

getS3method(“print”,“table”) ## function (x, digits = getOption(“digits”), quote = FALSE, na.print = “”, ## zero.print = “0”, justify = “none”, …) ## { ## d <- dim(x) ## if (any(d == 0)) { ## cat(“< table of extent”, paste(d, collapse = “ x “), ## “>\n”) ## return(invisible(x)) ## } ## xx <- format(unclass(x), digits = digits, justify = justify) ## if (any(ina <- is.na(x))) ## xx[ina] <- na.print ## if (zero.print != “0” && any(i0 <- !ina & x == 0)) ## xx[i0] <- zero.print ## if (is.numeric(x) || is.complex(x)) ## print(xx, quote = quote, right = TRUE, …) ## else print(xx, quote = quote, …) ## invisible(x) ## } ## ##

The other way around it is possible to list all generic functions that have a specific method for a given class.

You can also list all generics that have a method for a given class:

methods(class = “data.frame”) ## [1] [ [[ [[<- ## [4] [<- $ $<- ## [7] aggregate anyDuplicated as.data.frame ## [10] as.list as.matrix by ## [13] cbind coerce dim ## [16] dimnames dimnames<- droplevels ## [19] duplicated edit format ## [22] formula head initialize ## [25] is.na Math merge ## [28] na.exclude na.omit Ops ## [31] plot print prompt ## [34] rbind row.names row.names<- ## [37] rowsum show slotsFromS3 ## [40] split split<- stack ## [43] str subset summary ## [46] Summary t tail ## [49] transform unique unstack ## [52] within ## see ‘?methods’ for accessing help and source code

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

Интервал:

Закладка:

Сделать

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

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


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

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

x