Book Image

Data Analysis with R, Second Edition - Second Edition

Book Image

Data Analysis with R, Second Edition - Second Edition

Overview of this book

Frequently the tool of choice for academics, R has spread deep into the private sector and can be found in the production pipelines at some of the most advanced and successful enterprises. The power and domain-specificity of R allows the user to express complex analytics easily, quickly, and succinctly. Starting with the basics of R and statistical reasoning, this book dives into advanced predictive analytics, showing how to apply those techniques to real-world data though with real-world examples. Packed with engaging problems and exercises, this book begins with a review of R and its syntax with packages like Rcpp, ggplot2, and dplyr. From there, get to grips with the fundamentals of applied statistics and build on this knowledge to perform sophisticated and powerful analytics. Solve the difficulties relating to performing data analysis in practice and find solutions to working with messy data, large data, communicating results, and facilitating reproducibility. This book is engineered to be an invaluable resource through many stages of anyone’s career as a data analyst.
Table of Contents (24 chapters)
Title Page
Copyright and Credits
Packt Upsell


If we need to perform some computation that isn't already a function in R a multiple number of times, we usually do so by defining our own functions. A custom function in R is defined using the following syntax:

  > <- function(argument1, argument2, ...){ 
  +   # some functionality 
  + } 

For example, if we wanted to write a function that determined if a number supplied as an argument was even, we can do so in the following manner:

  > is.even <- function(a.number){ 
  +   remainder <- a.number %% 2 
  +   if(remainder==0) 
  +     return(TRUE) 
  +   return(FALSE) 
  + } 
  > # testing it 
  > is.even(10) 
  [1] TRUE 
  > is.even(9) 
  [1] FALSE

As an example of a function that takes more than one argument, let's generalize the preceding function by creating a function that determines whether the first argument is divisible by its second argument:

  > <- function(large.number, smaller.number){ 
  +   if(large.number %% smaller.number != 0) 
  +     return(FALSE) 
  +   return(TRUE) 
  + } 
  > # testing it 
  >, 2) 
  [1] TRUE 
  >, 3) 
  [1] FALSE 
  >, 3) 
  [1] TRUE

Our function, is.even(), could now be rewritten simply as follows:

  > is.even <- function(num){ 
  +, 2) 
  + } 

It is very common in R to want to apply a particular function to every element of a vector. Instead of using a loop to iterate over the elements of a vector, as we would do in many other languages, we use a function called sapply() to perform this. sapply() takes a vector and a function as its arguments. It then applies the function to every element and returns a vector of results. We can use sapply() in this manner to find out which digits in Jenny's phone number are even:

  > sapply(our.vect, is.even) 

This worked great because sapply takes each element and uses it as the argument in is.even(), which takes only one argument. If you wanted to find the digits that are divisible by three, it would require a little bit more work.

One option is just to define a function,, that takes only one argument and use this in sapply. The more common solution, however, is to define an unnamed function that does just that in the body of the sapply function call:

  > sapply(our.vect, function(num){, 3)}) 

Here, we essentially created a function that checks whether its argument is divisible by three, except we don't assign it to a variable and use it directly in the sapply body instead. These one-time-use unnamed functions are called anonymous functions or lambda functions. (The name comes from Alonzo Church's invention of the lambda calculus, if you were wondering.)

This is somewhat of an advanced usage of R, but it is very useful as it comes up very often in practice.

If we wanted to extract the digits in Jenny's phone number that are divisible by both, two and three, we can write it as follows:

  > where.even <- sapply(our.vect, is.even) 
  > where.div.3 <- sapply(our.vect, function(num){ 
  +, 3)}) 
  > # "&" is like the "&&" and operator but for vectors  
  > our.vect[where.even & where.div.3] 
  [1] 6 0


Note that if we wanted to be sticklers, we would have a clause in the function bodies to preclude a modulus computation, where the first number was smaller than the second. If we had, our function would not have erroneously indicated that 0 was divisible by two and three. I'm not a stickler, though, so the function will remain as is. Fixing this function is left as an exercise for the (stickler) reader.