Blogs home

I always find it difficult to pick highlights from a conference and the eRum 2018 team did a fantastic job of making it difficult for me once again, so here goes…

Day One

The first day offered a huge choice in workshops, but teaching one of them meant we didn’t make it to any of the others. However, everyone we spoke to had great things to say about them all. In fact, we were overwhelmed by the turnout for our own workshop on the keras package (and we have to give a shout out to Mark Sellors for setting up and monitoring the server for us). By the way, if you missed out, you can sign up for the workshop at EARL London in September.

Day Two

Tuesday might have been a rainy start outside but inside we were mesmerised by the transparent roof in the Akvarium Klub. For team Mango, the morning mostly involved cat restocking, so we were really grateful for the live streaming that enabled us to keep up with everything going on in the main room.

My favourite presentations included:

Having newly been introduced to the recipes package I particularly enjoyed seeing Edwin Thoen talk about how to add your own data preparation steps and checks.

Olga Mierzwa-Sulima presented six packages to add functionality to shiny apps. These cover UI aspects like using semantic elements in shiny or easily exchanging themes for the app as well as user management aspects like authentication and controlling the level of access for different users. She also covered additional functionality like making routing possible with shiny and building multi-language apps.

Jeroen Ooms spoke about using Rust code in R packages. Rust is a new system programming language and can be an alternative to C/C++. Jeroen mentioned several advantages including Rust being memory safe and as fast as C/C++ while being far safer. It ships with a native package manager (cargo) and does not need a runtime library which means that the binary (R) package does not depend on Rust or cargo. He stressed that it’s easy to wrap Rust libraries into R packages so hopefully soon the selection of tools available from R will be even more varied.

A particular highlight for Doug Ashton came on Tuesday afternoon with three complementary talks on machine learning. With all the buzz to deal with in the ML world right now, Doug thought the practical talks from three level-headed practioners were very useful:

First Erin LeDell, Chief Machine Learning Scientist at h2o, gave an excellent talk on their automl package – a system they’ve been working hard on to run several different algorithms and select the best. Doug’s favourite part was their automated model ensembling (aka model stacking) that provides the best mix of all the algorithms.

Szilárd Pafka, Chief Scientist at Epoch followed on with a presentation on the provactively titled “Better than deep learning: Gradient Boosted Machines in R”, where he talked about why the majority of ML problems he sees are not best suited for deep learning. Szilárd also gave a nice overview of the best performing algorithms for gbm. (Doug’s note to self was to check out Microsoft’s lightgbm and xgboost with gpu.)


Going back to the theme of automation Andrie de Vries, Solutions Engineer at RStudio, took us through how to tune your tensorflow models using the tfruns package to run grid/random search over the hyperparameter space. This is very timely as we are often asked about how to select the right network topology and until now we’ve largely hand-tuned. Andrie then took us through an example where deep learning certainly is the right choice—image/pattern recognition with convolutional neural nets (CNNs)—and taking our example from the keras workshop significantly improved the accuracy with automated tuning – 👏.

After the rainy to start the day we were all relieved to see it had cleared up by the time the evening event (a river cruise) came around – we were lucky to have stunning views of Budapest from the Danube; the sunset on the Parliament building with stormy skies overhead was incredible.

Day Three

On Wednesday morning Roger Bivand did a great job of talking us all through some of the very important history of R – you all knew “_” was once an assignment operator, right?

RStudio’s Barbara Borges Ribeiro showed off a cool shiny app for drilling down into data and making use of the dynamic insertion of UI. Unfortunately I missed her talk, but managed to get a demo of it later in the day – you can take a look at the app on GitHub.

The biggest highlight for me though were the people. Without a doubt it was one of the friendliest conferences I have attended. Everyone was happy to share their experiences, answer your questions and point you in the direction of tools to look at later. Importantly, everyone was made to feel welcome, from the most-experienced to the newest R users.

The videos from all talks are being made available, check the conference homepage for the link.

Congratulations to the whole organising committee, led by Gergely Daroczi, for putting on such a great event. Mango are certainly looking forward to the next eRum conference!

Blogs home

In this blog post I explore the purrr package (member of tidyverse collection) and its use within a data scientist’s code. I aim to present the case for using the purrr functions and through the use of examples compare them with base R functionality. To do this, we will concentrate on two typical coding scenarios in base R: 1) loops and 2) the suite of apply functions and then compare them with their relevant counterpart map functions in the purrr package.

However, before I start, I wanted to make it clear that I do sympathise with those of you whose first reaction to purrr is “but I can do all this stuff in base R”. Putting that aside, the obvious first obstacle for us to overcome is to lose the notion of “if it’s not broken why change it” and open our ‘coding’ minds to change. At least, I hope you agree with me that the silver lining of this kind of exercise is to satisfy ones curiosity about the purrrpackage and maybe learn something new!

Let us first briefly describe the concept of functional programming (FP) in case you are not familiar with it.

Functional programming (FP)

R is a functional programming language which means that a user of R has the necessary tools to create and manipulate functions. There is no need to go into too much depth here but it suffices to know that FP is the process of writing code in a structured way and through functions remove code duplications and redundancies. In effect, computations or evaluations are treated as mathematical functions and the output of a function only depends on the values of its inputs – known as arguments. FP ensures that any side-effects such as changes in state do not affect the expected output such that if you call the same function twice with the same arguments the function returns the same output.

For those that are interested to find out more, I suggest reading Hadley Wickham’s Functional Programmingchapter in the “Advanced R” book. The companion website for this can be found at: http://adv-r.had.co.nz/

The purrr package, which forms part of the tidyverse ecosystem of packages, further enhances the functional programming aspect of R. It allows the user to write functional code with less friction in a complete and consistent manner. The purrr functions can be used, among other things, to replace loops and the suite of apply functions.

Let’s talk about loops

The motivation behind the examples we are going to look at involve iterating in R for various scenarios. For example, iterate over elements of a vector or list, iterate over rows or columns of a matrix … the list (pun intended) can go on and on!

One of the first things that one gets very excited to ‘play’ when learning to use R – at least that was the case for me – is loops! Lot’s of loops, elaborate, complex… dare I say never ending infinite loops (queue hysteric laughter emoji). Joking aside, it is usually the default answer to a problem that involves iteration of some sort as I demonstrate below.

# Create a vector of the mean values of all the columns of the mtcars dataset
# The long repetitive way
mean_vec <- c(mean(mtcars$mpg),mean(mtcars$cyl),mean(mtcars$disp),mean(mtcars$hp),
              mean(mtcars$drat),mean(mtcars$wt),mean(mtcars$qsec),mean(mtcars$vs),
              mean(mtcars$am),mean(mtcars$gear),mean(mtcars$carb))
mean_vec
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500

# The loop way
mean_vec_loop <- vector("double", ncol(mtcars))
for (i in seq_along(mtcars)) {
  mean_vec_loop[[i]] <- mean(mtcars[[i]])
}
mean_vec_loop
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500

The resulting vectors are the same and the difference in speed (milliseconds) is negligible. I hope that we can all agree that the long way is definitely not advised and actually is bad coding practice, let alone the frustration (and error-prone task) of copy/pasting. Having said that, I am sure there are other ways to do this – I demonstrate this later using lapply – but my aim was to show the benefit of using a for loop in base R for an iteration problem.

Now imagine if in the above example I wanted to calculate the variance of each column as well…

# Create two vectors of the mean and variance of all the columns of the mtcars dataset

# For mean
mean_vec_loop <- vector("double", ncol(mtcars))
for (i in seq_along(mtcars)) {
  mean_vec_loop[[i]] <- mean(mtcars[[i]])
}
mean_vec_loop
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500

#For variance
var_vec_loop <- vector("double", ncol(mtcars))
for (i in seq_along(mtcars)) {
  var_vec_loop[[i]] <- var(mtcars[[i]])
}
var_vec_loop
 [1] 3.632410e+01 3.189516e+00 1.536080e+04 4.700867e+03 2.858814e-01
 [6] 9.573790e-01 3.193166e+00 2.540323e-01 2.489919e-01 5.443548e-01
[11] 2.608871e+00

# Or combine both calculations in one loop
for (i in seq_along(mtcars)) {
  mean_vec_loop[[i]] <- mean(mtcars[[i]])
  var_vec_loop[[i]] <- var(mtcars[[i]])
}
mean_vec_loop
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500
var_vec_loop
 [1] 3.632410e+01 3.189516e+00 1.536080e+04 4.700867e+03 2.858814e-01
 [6] 9.573790e-01 3.193166e+00 2.540323e-01 2.489919e-01 5.443548e-01
[11] 2.608871e+00

Now let us assume that we know that we want to create these vectors not just for the mtcars dataset but for other datasets as well. We could in theory copy/paste the for loops and just change the dataset we supply in the loop but one should agree that this action is repetitive and could result to mistakes. Instead we can generalise this into functions. This is where FP comes into play.

# Create two functions that returns the mean and variance of the columns of a dataset

# For mean
col_mean <- function(df) {
  output <- vector("double", length(df))
  for (i in seq_along(df)) {
    output[[i]] <- mean(df[[i]])
  }
  output
}
col_mean(mtcars)
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500

#For variance
col_variance <- function(df) {
  output <- vector("double", length(df))
  for (i in seq_along(df)) {
    output[[i]] <- var(df[[i]])
  }
  output
}
col_variance(mtcars)
 [1] 3.632410e+01 3.189516e+00 1.536080e+04 4.700867e+03 2.858814e-01
 [6] 9.573790e-01 3.193166e+00 2.540323e-01 2.489919e-01 5.443548e-01
[11] 2.608871e+00

Why not take this one step further and take full advantage of R’s functional programming tools by creating a function that takes as an argument a function! Yes, you read it correctly… a function within a function!

Why do we want to do that? Well, the code for the two functions above, as clean as it might look, is still repetitive and the only real difference between col_mean and col_var is the mathematical function that we are calling. So why not generalise this further?

# Create a function that returns a computational value (such as mean or variance)
# for a given dataset

col_calculation <- function(df,fun) {
  output <- vector("double", length(df))
  for (i in seq_along(df)) {
    output[[i]] <- fun(df[[i]])
  }
  output
}
col_calculation(mtcars,mean)
 [1]  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
 [7]  17.848750   0.437500   0.406250   3.687500   2.812500
col_calculation(mtcars,var)
 [1] 3.632410e+01 3.189516e+00 1.536080e+04 4.700867e+03 2.858814e-01
 [6] 9.573790e-01 3.193166e+00 2.540323e-01 2.489919e-01 5.443548e-01
[11] 2.608871e+00

Did someone say apply?

I mentioned earlier that an alternative way to solve the problem is to use the apply function (or suite of applyfunctions such as lapply, sapply, vapply, etc). In fact, these functions are what we call Higher Order Functions. Similar to what we did earlier, these are functions that can take other functions as an argument.

The benefit of using higher order functions instead of a for loop is that they allow us to think about what code we are executing at a higher level. Think of it as: “apply this to that” rather than “take the first item, do this, take the next item, do this…”

I must admit that at first it might take a little while to get used to but there is definitely a sense of pride when you can improve your code by eliminating for loops and replace them with apply-type functions.

# Create a list/vector of the mean values of all the columns of the mtcars dataset
lapply(mtcars,mean) %>% head # Returns a list
$mpg
[1] 20.09062

$cyl
[1] 6.1875

$disp
[1] 230.7219

$hp
[1] 146.6875

$drat
[1] 3.596563

$wt
[1] 3.21725
sapply(mtcars,mean) %>% head # Returns a vector
       mpg        cyl       disp         hp       drat         wt 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250

Once again, speed of execution is not the issue and neither is the common misconception about loops being slow compared to apply functions. As a matter of fact the main argument in favour of using lapply or any of the purrr functions as we will see later is the pure simplicity and readability of the code. Full stop.

Enter the purrr

The best place to start when exploring the purrr package is the map function. The reader will notice that these functions are utilised in a very similar way to the apply family of functions. The subtle difference is that the purrr functions are consistent and the user can be assured of the output – as opposed to some cases when using for example sapply as I demonstrate later on.

# Create a list/vector of the mean values of all the columns of the mtcars dataset
map(mtcars,mean) %>% head # Returns a list
$mpg
[1] 20.09062

$cyl
[1] 6.1875

$disp
[1] 230.7219

$hp
[1] 146.6875

$drat
[1] 3.596563

$wt
[1] 3.21725
map_dbl(mtcars,mean) %>% head # Returns a vector - of class double
       mpg        cyl       disp         hp       drat         wt 
 20.090625   6.187500 230.721875 146.687500   3.596563   3.217250

Let us introduce the iris dataset with a slight modification in order to demonstrate the inconsistency that sometimes can occur when using the sapply function. This can often cause issues with the code and introduce mystery bugs that are hard to spot.

# Modify iris dataset
iris_mod <- iris
iris_mod$Species <- ordered(iris_mod$Species) # Ordered factor levels class(iris_mod$Species) # Note: The ordered function changes the class [1] "ordered" "factor" # Extract class of every column in iris_mod sapply(iris_mod, class) %>% str # Returns a list of the results
List of 5
 $ Sepal.Length: chr "numeric"
 $ Sepal.Width : chr "numeric"
 $ Petal.Length: chr "numeric"
 $ Petal.Width : chr "numeric"
 $ Species     : chr [1:2] "ordered" "factor"
sapply(iris_mod[1:3], class) %>% str # Returns a character vector!?!? - Note: inconsistent object type
 Named chr [1:3] "numeric" "numeric" "numeric"
 - attr(*, "names")= chr [1:3] "Sepal.Length" "Sepal.Width" "Petal.Length"

Since by default map returns a list one can ensure that an object of the same class is returned without any unexpected (and unwanted) surprises. This is inline with FP consistency.

# Extract class of every column in iris_mod
map(iris_mod, class) %>% str # Returns a list of the results
List of 5
 $ Sepal.Length: chr "numeric"
 $ Sepal.Width : chr "numeric"
 $ Petal.Length: chr "numeric"
 $ Petal.Width : chr "numeric"
 $ Species     : chr [1:2] "ordered" "factor"
map(iris_mod[1:3], class) %>% str # Returns a list of the results
List of 3
 $ Sepal.Length: chr "numeric"
 $ Sepal.Width : chr "numeric"
 $ Petal.Length: chr "numeric"

To further demonstrate the consistency of the purrr package in this type of setting, the map_*() functions (see below) can be used to return a vector of the expected type, otherwise you get an informative error.

  • map_lgl() makes a logical vector.
  • map_int() makes an integer vector.
  • map_dbl() makes a double vector.
  • map_chr() makes a character vector.
# Extract class of every column in iris_mod
map_chr(iris_mod[1:4], class) %>% str # Returns a character vector
 Named chr [1:4] "numeric" "numeric" "numeric" "numeric"
 - attr(*, "names")= chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
map_chr(iris_mod, class) %>% str # Returns a meaningful error
Error: Result 5 is not a length 1 atomic vector

# As opposed to the equivalent base R function vapply
vapply(iris_mod[1:4], class, character(1)) %>% str  # Returns a character vector
 Named chr [1:4] "numeric" "numeric" "numeric" "numeric"
 - attr(*, "names")= chr [1:4] "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
vapply(iris_mod, class, character(1)) %>% str  # Returns a possibly harder to understand error
Error in vapply(iris_mod, class, character(1)): values must be length 1,
 but FUN(X[[5]]) result is length 2

It is worth noting that if the user does not wish to rely on tidyverse dependencies they can always use base R functions but need to be extra careful of the potential inconsistencies that might arise.

Multiple arguments and neat tricks

In case we wanted to apply a function to multiple vector arguments we have the option of mapply from base R or the map2 from purrr.

# Create random normal values from a list of means and a list of standard deviations
mu <- list(10, 100, -100)
sigma <- list(0.01, 1, 10)

mapply(rnorm, n=5, mu, sigma, SIMPLIFY = FALSE) # I need SIMPLIFY = FALSE because otherwise I get a matrix
[[1]]
[1] 10.002750 10.001843  9.998684 10.008720  9.994432

[[2]]
[1] 100.54979  99.64918 100.00214 102.98765  98.49432

[[3]]
[1]  -82.98467  -99.05069  -95.48636  -97.43427 -110.02194

map2(mu, sigma, rnorm, n = 5)
[[1]]
[1] 10.00658 10.00005 10.00921 10.02296 10.00840

[[2]]
[1]  98.92438 100.86043 100.20079  97.02832  99.88593

[[3]]
[1] -113.32003  -94.37817  -86.16424  -97.80301 -105.86208

The map2 function can easily extend to further arguments – not just two as in the example above – and that is where the pmap function comes in.

I also thought of sharing a couple of neat tricks that one can use with the map function.

  1. Say you want to fit a linear model for every cylinder type in the mtcars dataset. You can avoid code duplication and do it as follows:
# Split mtcars dataset by cylinder values and then fit a simple lm
models <- mtcars %>% 
  split(.$cyl) %>% # Split by cylinder into 3 lists
  map(function(df) lm(mpg ~ wt, data = df)) # Fit linear model for each list
  1. Say we are using a function, such as sqrt (calculate square root), on a list that contains a non-numeric element. The base R function lapply throws an error and execution stops without knowing what caused the error. The safely function of purrr completes execution and the user can identify what caused the error.
x <- list(1, 2, 3, "e", 5)

# Base R
lapply(x, sqrt)
Error in FUN(X[[i]], ...): non-numeric argument to mathematical function

# purrr package
safe_sqrt <- safely(sqrt)
safe_result_list <- map(x, safe_sqrt) %>% transpose
safe_result_list$result
[[1]]
[1] 1

[[2]]
[1] 1.414214

[[3]]
[1] 1.732051

[[4]]
NULL

[[5]]
[1] 2.236068

Conclusion

Overall, I think it is fair to say that using higher order functions in R is a great way to improve ones code. With that in mind, my closing remark for this blog post is to simply re-iterate the benefits of using the purrrpackage. That is:

  • The output is consistent.
  • The code is easier to read and write.

If you enjoyed learning about purrr, then you can join us at our purrr workshop at this years EARL London – early bird tickets are available now!

Blogs home

Another month, another sweepstake to raise money for the Bath Cats & Dogs home!

This time, we picked the Eurovision song contest as our sweepstake of choice. After enjoying my first experience of using R to randomise the names for the previous sweepstake I decided to give it another go, but with a few tweaks.

Soundcheck

During my first attempt in R, issues arose when I had been (innocently!) allocated the favourite horse to win. I had no way to prove that the R code had made the selection, as my work was not reproducible.

So with the cries of “cheater!” and “fix!”” still ringing in my ears, we started by setting a seed. This meant that if someone else was to replicate my code they would get the same results; therefore removing the dark smudge against my good name.

At random I selected the number 6 at which to set my seed.

set.seed(6)

I next compiled my lists of people and Eurovision countries and associated them with correlating objects.

people_list <- c(
    "Andy M",
    "Adam",
    "Laura",
    "Rachel",
    "Owen",
    "Yvi",
    "Karis",
    "Toby",
    "Jen",
    "Matty G",
    "Tatiana",
    "Amanda",
    "Chrissy",
    "Lisa",
    "Lisa",
    "Ben",
    "Ben",
    "Robert",
    "Toby",
    "Matt A",
    "Lynn",
    "Ruth",
    "Julian",
    "Karina",
    "Colin",
    "Colin")
countries_list <- c(
    "Albania",
    "Australia",
    "Austria",
    "Bulgaria",
    "Cyprus",
    "Czech Rep",
    "Denmark",
    "Estonia",
    "Finland",
    "France",
    "Germany",
    "Hungary",
    "Ireland",
    "Israel",
    "Italy",
    "Lithuania",
    "Moldova",
    "Norway",
    "Portugal",
    "Serbia",
    "Slovenia",
    "Spain",
    "Sweden",
    "The Netherlands",
    "Ukraine",
    "United Kingdom"
  )

Once I had the lists associated with objects, I followed the same steps as my previous attempt in R. I put both objects into data frames and then used the sample function to jumble up the names.

assign_countries <- data.frame(people = people_list,
                               countries = sample(countries_list))

Task complete!

Fate had delivered me Denmark, who were nowhere near the favourites at the point of selection. I sighed with relief knowing that I had no chance of winning again and that perhaps maybe now I could start to re-build my reputation as an honest co-worker...

Encore

Before I finished my latest foray into R, we decided to create a function for creating sweepstakes in R.

I was talked down from picking the name SweepstakeizzleR and decided upon the slightly more sensible sweepR.

I entered the desired workings of the function, which followed from the above work in R.

sweepR <- function(a, b, seed = 1234){
 set.seed(seed)
 data.frame(a, sample(b))
}

Once done, I could use my newly created function to complete the work I had done before but in a much timelier fashion.

sweepR(people_list, countries_list)

My very first function worked! Using a function like sweepR will allow me to reliably reproduce the procedures I need for whatever task I'm working on. In this case it has enabled me to create a successfully random sweepstake mix of names and entries.

WinneR

With great relief Israel won Eurovision and I was very happy to hand over the prize to Amanda.

I really enjoyed learning a little more about R and how I can create functions to streamline my work. Hopefully another reason will come up for me to learn even more soon!

Blogs home

We are excited to annouce that the goodpractice package is now available on CRAN. The package gives advice about good practices when building R packages. Advice includes functions and syntax to avoid, package structure, code complexity, code formatting, etc.

You can install the CRAN version via

install.packages("goodpractice")

Building R packages

Building an R package is a great way of encapsulating code, documentation and data in a single testable and easily distributable unit.

For a package to be distributed via CRAN, it needs to pass a set of checks implemented in R CMD check, such as: Is there minimal documentation, e.g., are all arguments of exported functions documented? Are all dependencies declared?

These checks are helpful in developing a solid R package but they don’t check for several other good practices. For example, a package does not need to contain any tests but is it good practice to include some. Following a coding standard helps readability. Avoiding overly complex functions reduces the risk of bugs. Including an URL for bug reports lets people more easily report bugs if they find any.

What the goodpractice package does

Tools for automatically checking several of the above mentioned aspects already exist and the goodpracticepackage bundles the checks from rcmdcheck with code coverage through the covr package, source code linting via the lintr package and cyclompatic complexity via the cyclocomp package and augments it with some further checks on good practice for R package development such as avoiding T and F in favour of TRUEand FALSE. It provides advice on which practices to follow and which to avoid.

You can use goodpractice checks as a reminder for you and your collegues – and if you have custom checks to run, you can make goodpractice run those as well!

How to use goodpractice

The main fuction goodpractice() (and its alias gp()) takes the path to the source code of a package as its first argument. The goodpractice package contains the source for a simple package which violates some good practices. We’ll use this for the examples.

library(goodpractice)

# get path to example package
pkg_path <- system.file("bad1", package = "goodpractice")

# run gp() on it
g <- gp(pkg_path) #> Preparing: covr
#> Warning in MYPREPS[[prep]](state, quiet = quiet): Prep step for test
#> coverage failed.
#> Preparing: cyclocomp
#> Skipping 2 packages ahead of CRAN: callr, remotes
#> Installing 1 packages: stringr
#> 
#>   There is a binary version available but the source version is
#>   later:
#>         binary source needs_compilation
#> stringr  1.3.0  1.3.1             FALSE
#> installing the source package 'stringr'
#> Preparing: description
#> Preparing: lintr
#> Preparing: namespace
#> Preparing: rcmdcheck

# show the result
g
#> ── GP badpackage ──────────────────────────────────────────────────────────
#> 
#> It is good practice to
#> 
#>   ✖ not use "Depends" in DESCRIPTION, as it can cause name
#>     clashes, and poor interaction with other packages. Use
#>     "Imports" instead.
#>   ✖ omit "Date" in DESCRIPTION. It is not required and it gets
#>     invalid quite often. A build date will be added to the package
#>     when you perform `R CMD build` on it.
#>   ✖ add a "URL" field to DESCRIPTION. It helps users find
#>     information about your package online. If your package does
#>     not have a homepage, add an URL to GitHub, or the CRAN package
#>     package page.
#>   ✖ add a "BugReports" field to DESCRIPTION, and point it to a bug
#>     tracker. Many online code hosting services provide bug
#>     trackers for free, https://github.com, https://gitlab.com,
#>     etc.
#>   ✖ omit trailing semicolons from code lines. They are not needed
#>     and most R coding standards forbid them
#> 
#>     R/semicolons.R:4:30
#>     R/semicolons.R:5:29
#>     R/semicolons.R:9:38
#> 
#>   ✖ not import packages as a whole, as this can cause name clashes
#>     between the imported packages. Instead, import only the
#>     specific functions you need.
#>   ✖ fix this R CMD check ERROR: VignetteBuilder package not
#>     declared: ‘knitr’ See section ‘The DESCRIPTION file’ in the
#>     ‘Writing R Extensions’ manual.
#>   ✖ avoid 'T' and 'F', as they are just variables which are set to
#>     the logicals 'TRUE' and 'FALSE' by default, but are not
#>     reserved words and hence can be overwritten by the user.
#>     Hence, one should always use 'TRUE' and 'FALSE' for the
#>     logicals.
#> 
#>     R/tf.R:NA:NA
#>     R/tf.R:NA:NA
#>     R/tf.R:NA:NA
#>     R/tf.R:NA:NA
#>     R/tf.R:NA:NA
#>     ... and 4 more lines
#> 
#> ───────────────────────────────────────────────────────────────────────────

So with this package, we’ve done a few things in the DESCRIPTION file for which there are reasons not to do them, have unnecessary trailing semicolons in the code and used T and F for TRUE and FALSE. The output of gp() will tell you what isn’t considered good practice out of what you have already written. If that is in the R code itself, it will also point you to the location of your faux-pas. In general, the messages are supposed to not only point out to you what you might want to avoid but also why.

Custom checks

The above example tries to run all 230 checks available, to see the full list use all_checks(). You can customise the set of checks run by selecting only those default checks you are intersted in and by adding your own checks.

If you only want to run a subset of the checks, e.g., just the check on the URL field in the DESCRIPTION, you can specify the checks by name:

# what is the name of the check?
grep("url", all_checks(), value = TRUE)
#> [1] "description_url"

# run only this check
gp(pkg_path, checks = "description_url")
#> Preparing: description
#> ── GP badpackage ──────────────────────────────────────────────────────────
#> 
#> It is good practice to
#> 
#>   ✖ add a "URL" field to DESCRIPTION. It helps users find
#>     information about your package online. If your package does
#>     not have a homepage, add an URL to GitHub, or the CRAN package
#>     package page.
#> ───────────────────────────────────────────────────────────────────────────

Additional checks can be used in gp() via the extra_checks argument. This should be a named list of checkobjects as returned by the make_check() function.

# make a simple version of the T/F check
check_simple_tf <- make_check( description = "TRUE and FALSE is used, not T and F", gp = "avoid 'T' and 'F', use 'TRUE' and 'FALSE' instead.", check = function(state) { length(tools::checkTnF(dir = state$path)) == 0 } ) gp(pkg_path, checks = c("description_url", "simple_tf"), extra_checks = list(simple_tf = check_simple_tf)) #> Preparing: description
#> ── GP badpackage ──────────────────────────────────────────────────────────
#> 
#> It is good practice to
#> 
#>   ✖ add a "URL" field to DESCRIPTION. It helps users find
#>     information about your package online. If your package does
#>     not have a homepage, add an URL to GitHub, or the CRAN package
#>     package page.
#>   ✖ avoid 'T' and 'F', use 'TRUE' and 'FALSE' instead.
#> ───────────────────────────────────────────────────────────────────────────

For more details on creating custom checks, please see the vignette Custom Checks.

Acknowledgements

This package was written by Gábor Csárdi with contributions by Noam Ross, Neal Fultz, Douglas Ashton, Marcel Ramos, Joseph Stachelek, and myself. Special thanks for the input and feedback to the rOpenScileadership team and community as well as everybody who opened issues!

Feedback

If you have any feedback, please consider opening an issue on GitHub.

Blogs home

(Or, how to write a Shiny app.R file that only contains a single line of code)

This post is long overdue. The information contained herein has been built up over years of deploying and hosting Shiny apps, particularly in production environments, and mainly where those Shiny apps are very large and contain a lot of code.

Last year, during some of my conference talks, I told the story of Mango’s early adoption of Shiny and how it wasn’t always an easy path to production for us. In this post I’d like to fill in some of the technical background and provide some information about Shiny app publishing and packaging that is hopefully useful to a wider audience.

I’ve figured out some of this for myself, but the most pivotal piece of information came from Shiny creator, Joe Cheng. Joe told me some time ago, that all you really need in an app.R file is a function that returns a Shiny application object. When he told me this, I was heavily embedded in the publication side and I didn’t immediately understand the implications.

Over time though I came to understand the power and flexibility that this model provides and, to a large extent, that’s what this post is about.

What is Shiny?

Hopefully if you’re reading this you already know, but Shiny is a web application framework for R. It allows R users to develop powerful web applications entirely in R without having to understand HTML, CSS and JavaScript. It also allows us to embed the statistical power of R directly into those web applications.

Shiny apps generally consist of either a ui.R and a server.R (containing user interface and server-side logic respectively) or a single app.R which contains both. Why package a Shiny app anyway?

If your app is small enough to fit comfortably in a single file, then packaging your application is unlikely to be worth it. As with any R script though, when it gets too large to be comfortably worked with as a single file, it can be useful to break it up into discrete components.

Publishing a packaged app will be more difficult, but to some extent that will depend on the infrastructure you have available to you.

Pros of packaging

Packaging is one of the many great features of the R language. Packages are fairly straightforward, quick to create and you can build them with a host of useful features like built-in documentation and unit tests.

They also integrate really nicely into Continuous Integration (CI) pipelines and are supported by tools like Travis. You can also get test coverage reports using things like codecov.io.

They’re also really easy to share. Even if you don’t publish your package to CRAN, you can still share it on GitHub and have people install it with devtools, or build the package and share that around, or publish the package on a CRAN-like system within your organisation’s firewall.

Cons of packaging

Before you get all excited and start to package your Shiny applications, you should be aware that — depending on your publishing environment — packaging a Shiny application may make it difficult or even impossible to publish to a system like Shiny Server or RStudio Connect, without first unpacking it again.

* Since time of writing this information is now incorrect. Check out https://thinkr-open.github.io/golem/articles/c_deploy.html for more information on deploying packaged shinyapps to shiny server, shinyapps.io and rsconnect.

A little bit of Mango history

This is where Mango were in the early days of our Shiny use. We had a significant disconnect between our data scientists writing the Shiny apps and the IT team tasked with supporting the infrastructure they used. This was before we’d committed to having an engineering team that could sit in the middle and provide a bridge between the two.

When our data scientists would write apps that got a little large or that they wanted robust tests and documentation for, they would stick them in packages and send them over to me to publish to our original Shiny Server. The problem was: R packages didn’t really mean anything to me at the time. I knew how to install them, but that was about as far as it went. I knew from the Shiny docs that a Shiny app needs certain files (server.R and ui.R or an app.R) file, but that wasn’t what I got, so I’d send it back to the data science team and tell them that I needed those files or I wouldn’t be able to publish it.

More than once I got back a response along the lines of, “but you just need to load it up and then do runApp()”. But, that’s just not how Shiny Server works. Over time, we’ve evolved a set of best practices around when and how to package a Shiny application.

The first step was taking the leap into understanding Shiny and R packages better. It was here that I started to work in the space between data science and IT.

How to package a Shiny application

If you’ve seen the simple app you get when you choose to create a new Shiny application in RStudio, you’ll be familiar with the basic structure of a Shiny application. You need to have a UI object and a server function.

If you have a look inside the UI object you’ll see that it contains the html that will be used for building your user interface. It’s not everything that will get served to the user when they access the web application — some of that is added by the Shiny framework when it runs the application — but it covers off the elements you’ve defined yourself.

The server function defines the server-side logic that will be executed for your application. This includes code to handle your inputs and produce outputs in response.

The great thing about Shiny is that you can create something awesome quite quickly, but once you’ve mastered the basics, the only limit is your imagination.

For our purposes here, we’re going to stick with the ‘geyser’ application that RStudio gives you when you click to create a new Shiny Web Application. If you open up RStudio, and create a new Shiny app — choosing the single file app.R version — you’ll be able to see what we’re talking about. The small size of the geyser app makes it ideal for further study.

If you look through the code you’ll see that there are essentially three components: the UI object, the server function, and the shinyApp() function that actually runs the app.

Building an R package of just those three components is a case of breaking them out into the constituent parts and inserting them into a blank package structure. We have a version of this up on GitHub that you can check out if you want.

The directory layout of the demo project looks like this:

|-- DESCRIPTION
|-- LICENSE
|-- NAMESPACE
|-- R
|   |-- launchApp.R
|   |-- shinyAppServer.R
|   `-- shinyAppUI.R
|-- README.md
|-- inst
|   `-- shinyApp
|       `-- app.R
|-- man
|   |-- launchApp.Rd
|   |-- shinyAppServer.Rd
|   `-- shinyAppUI.Rd
`-- shinyAppDemo.Rproj

Once the app has been adapted to sit within the standard R package structure we’re almost done. The UI object and server function don’t really need to be exported, and we’ve just put a really thin wrapper function around shinyApp() — I’ve called it launchApp() — which we’ll actually use to launch the app. If you install the package from GitHub with devtools, you can see it in action.

library(shinyAppDemo)
launchApp()

This will start the Shiny application running locally.

The approach outlined here also works fine with Shiny Modules, either in the same package, or called from a separate package.

And that’s almost it! The only thing remaining is how we might deploy this app to Shiny server (including Shiny Server Pro) or RStudio Connect.

Publishing your packaged Shiny app

We already know that Shiny Server and RStudio Connect expect either a ui.R and a server.R or an app.R file. We’re running our application out of a package with none of this, so we won’t be able to publish it until we fix this problem.

The solution we’ve arrived at is to create a directory called ‘shinyApp’ inside the inst directory of the package. For those of you who are new to R packaging, the contents of the ‘inst’ directory are essentially ignored during the package build process, so it’s an ideal place to put little extras like this.

The name ‘shinyApp’ was chosen for consistency with Shiny Server which uses a ‘shinyApps’ directory if a user is allowed to serve applications from their home directory.

Inside this directory we create a single ‘app.R’ file with the following line in it:

shinyAppDemo::launchApp()

And that really is it. This one file will allow us to publish our packaged application under some circumstances, which we’ll discuss shortly.

Here’s where having a packaged Shiny app can get tricky, so we’re going to talk you through the options and do what we can to point out the pitfalls.

Shiny Server and Shiny Server Pro

Perhaps surprisingly — given that Shiny Server is the oldest method of Shiny app publication — it’s also the easiest one to use with these sorts of packaged Shiny apps. There are basically two ways to publish on Shiny Server. From your home directory on the server — also known as self-publishing — or publishing from a central location, usually the directory ‘/srv/shiny-server’.

The central benefit of this approach is the ability to update the application just by installing a newer version of the package. Sadly though, it’s not always an easy approach to take.

Apps served from home directory (AKA self-publishing)

The first publication method is from a users’ home directory. This is generally used in conjunction with RStudio Server. In the self-publishing model, Shiny Server (and Pro) expect apps to be found in a directory called ‘ShinyApps’, within the users home directory. This means that if we install a Shiny app in a package the final location of the app directory will be inside the installed package, not in the ShinyApps directory. In order to work around this, we create a link from where the app is expected to be, to where it actually is within the installed package structure.

So in the example of our package, we’d do something like this in a terminal session:

# make sure we’re in our home directory
cd
# change into the shinyApps directory
cd shinyApps
# create a link from our app directory inside the package
ln -s /home/sellorm/R/x86_64-pc-linux-gnu-library/3.4/shinyAppDemo/shinyApp ./testApp

Note: The path you will find your libraries in will differ from the above. Check by running .libPaths()[1] and then dir(.libPaths()[1]) to see if that’s where your packages are installed.

Once this is done, the app should be available at ‘http://<server-address>:3838//’ and can be updated by updating the installed version of the package. Update the package and the updates will be published via Shiny Server straight away.

Apps Server from a central location (usually /srv/shiny-server)

This is essentially the same as above, but the task of publishing the application generally falls to an administrator of some sort.

Since they would have to transfer files to the server and log in anyway, it shouldn’t be too much of an additional burden to install a package while they’re there. Especially if that makes life easier from then on.

The admin would need to transfer the package to the server, install it and then create a link — just like in the example above — from the expected location, to the installed location.

The great thing with this approach is that when updates are due to be installed the admin only has to update the installed package and not any other files.

RStudio Connect

Connect is the next generation Shiny Server. In terms of features and performance, it’s far superior to its predecessor. One of the best features is the ability to push Shiny app code directly from the RStudio IDE. For the vast majority of users, this is a huge productivity boost, since you no longer have to wait for an administrator to publish your app for you.

Since publishing doesn’t require anyone to directly log into the server as part of the publishing process, there aren’t really any straightforward opportunities to install a custom package. This means that, in general, publishing a packaged shiny application isn’t really possible.

There’s only one real workaround for this situation that I’m aware of. If you have an internal CRAN-like repository for your custom packages, you should be able to use that to update Connect, with a little work.

You’d need to have your dev environment and Connect hooked up to the same repo. The updated app package needs to be available in that repo and installed in your dev environment. Then, you could publish and then update the single line app.R for each successive package version you publish.

Connect uses packrat under the hood, so when you publish the app.R the packrat manifest will also be sent to the server. Connect will use the manifest to decide which packages are required to run your app. If you’re using a custom package this would get picked up and installed or updated during deployment.

shinyapps.io

It’s not currently possible to publish a packaged application to shinyapps.io. You’d need to make sure your app followed the accepted conventions for creating Shiny apps and only uses files, rather than any custom packages.

Conclusion

Packaging Shiny apps can be a real productivity boon for you and your team. In situations where you can integrate that process into other processes, such as automatically running your unit tests or automated publishing it can also help you adopt devops-style workflows.

However, in some instances, the practice can actually make things worse and really slow you down. It’s essential to understand what the publishing workflow is in your organisation before embarking on any significant Shiny packaging project as this will help steer you towards the best course of action.

If you would like to find out how we can help you with Shiny, get in touch with us: sales@mango-solutions.com

Blogs home

We’re delighted to announce RStudio’s Garrett Grolemund as one of our Keynote Speakers at this year’s EARL London.

He will join Starcount’s Edwina Dunn and a whole host of brilliant speakers for the 5th EARL London Conference on 11-13 September at The Tower Hotel.

Garrett specialises in teaching people how to use R, which is why you’ll see his name on some brilliant resources, including video courses on Datacamp.com and O’Reilly media, his series of popular R cheat sheets distributed by RStudio, and as co-author of R for Data Science and Hands-On Programming with R. He also wrote the lubridate R package and works for RStudio as an advocate who trains engineers to do data science with R and the Tidyverse.

He earned his Phd in Statistics from Rice University in 2012 under the guidance of Hadley Wickham. Before that, he earned a Bachelor’s degree in Psychology from Harvard University and briefly attended law school before wising up.

Garrett is one of the foremost promoters of Shiny, R Markdown, and the Tidyverse, so we’re really looking forward to his keynote.

Don’t miss out on early bird tickets

Early bird tickets for all EARL Conferences are now available:
London: 11-13 September
Seattle: 7 November
Houston: 9 November
Boston: 13 November

Blogs home Featured Image

A definition of Data Science

Much of my time is spent talking to organisations looking to build a data science capability, or generally looking to use analytics to drive better decision making. As part of this, I’m often asked to present on a range of topics around data science. The two topics I’m asked to present on most are: ‘What is Data science?’ and ‘What is a Data Scientist?’. I thought I’d share how we at Mango define what Data science is, along with the reasoning behind our definition.

Where did the term Data science come from?

Professor Jeff Wu —the Coca-Cola Chair in Engineering Statistics at Georgia Institute of Technology— popularised the term ‘data science’ during a talk in 1997. Before this, the term statistician was widely used instead. Professor Wu felt that the title ‘Statistician’ no longer covered the array of work being done by statisticians, and that ‘Data Scientist’ better encapsulated the multi-facetted role.

So, surely defining what a Data Scientist is and what they do should be a simple task – just bring up an image of Professor Wu and reference his 1997 lecture and ask for questions. However, the original definition has evolved since then and, in fact, most data scientists I meet are unfamiliar with Professor Wu.

What does Data Science mean today?

As mentioned, what ‘Data science’ meant originally and what it means today are two very different things. To develop what Mango’s definition of Data science would be, we looked to the wider community to see what they were saying.

Twitter has given us some great definitions, such as:

One early definition of what a data scientist means, is from Josh Wills, current Director of Data Engineering at Slack. Back in 2012, Josh described a data scientist as follows:

This speaks more directly to the data scientist being a ‘merging’ of different skillsets – a mix of a ‘statistician’ and ‘software engineer’.

Drew Conway, now CEO of Alluvium, took this concept further with a heavily used venn diagram:

Beyond these definitions, I’ve heard a range of blunt comments about what a Data Scientists is and isn’t.

For example, at a recent data science event a speaker announced that “if you haven’t got a PhD then you’re not a data scientist”, which, of course, caused a fair amount of upset across the room of non-PhD-data-scientists!

Our interest at Mango in defining and understanding what a Data Scientist is, stems from the need to hire new talent. How do we describe the job? What skills must they have? Are our expectations too high?

We’ve seen some unrealistic job descriptions that say a data scientist should be able to:

  • Understand every analytic algorithm from the statistical or computer science world, including machine learning, deep learning and whatever other algorithm the hiring company has just read about in a blog post
  • Be an expert in a range of technologies including R, Python, Spark, Julia and a veritable zoo-ful of Apache projects
  • Be equally comfortable discussing complex error structures or speaking to the chief execs about analytic strategy

These people just don’t exist.

To me, the trouble with most definitions of a data scientist seem detached from an agreed definition of data science. If a data scientist is someone who does data science, then surely we need to agree on what that is before understanding the skills needed to perform it successfully?

Drumroll please…

As per my earlier statement, it is clear that today data science has come to represent a lot more than Professor Wu’s original definition. At Mango, after countless arguments heated discussions, we arrived at the following (very carefully worded) definition:

Data Science is…the proactive use of data and advanced analytics to drive better decision making.

The four key parts

‘Data’

I might be stating the obvious here, but we can’t do data science without the data. What’s interesting is that data science is often associated with the extremes of Doug Laney’s famous ‘3 V’s’:

  • Volume – the size of data to be analysed, driving data science’s ongoing associated with the world of ‘big data’
  • Variety – with algorithms focused on analysing a range of structured and unstructured data types (e.g. image, text, video) being developed faster perhaps than the business cases are understood
  • Velocity – the speed at which new data is created and speed of decision therefore required, leading to stream analytics and increased usage of machine learning approaches

However, data science is equally applicable to small, rectangular, static datasets in my mind.

‘Advanced analytics’

Generally, analytics can be thought of in four categories:

  • Descriptive Analytics: the study of ‘what happened?’ This is largely concerned with the reporting of results and summaries via static or interactive (e.g. dashboards) and is more commonly referred to as ‘Business Intelligence’
  • Diagnostic Analytics: a study of why something happened. This typically involves feature engineering, model development etc.
  • Predictive Analytics: the modelling of what might happen under different circumstances. This is a mechanism for understanding possible outcomes and the certainty (or lack of) with which we can make predictions
  • Prescriptive Analytics: the analysis of ‘optimum’ ways to behave in which to ‘minimise’ or ‘maximise’ a desired outcome.

As we progress through these categories, the complexity increases, and hopefully the value added to the business as well. But this isn’t a list of steps – you could jump straight to predictive or prescriptive analytics without touching on either descriptive or diagnostic.

It’s important to distinguish that data science is focused on advanced analytics and using the above definitions, this would mean dealing with everything beyond descriptive analytics.

‘Proactive’

‘Proactive’ was included to distinguish data science from the more traditional ‘statistical analysis’. In my experience, when I started my career as a statistician in industry, an organisation’s analytic function seemed a largely ‘reactive’ practice. Modern data science needs to be an active part of the business function and look for ways to improve the business.

‘To drive better decision making’

I think the last part of the definition is the most important part. If we ignore this, then there’s a danger of doing the expensive cool stuff and not actually adding any value. With organisations investing heavily in data science as an industry, we need to deliver – otherwise we may be in a situation where data science as a phrase becomes associated with high-cost initiatives that never truly add value.

We need to be very clear about something: we can use the best tech, leverage the most clever algorithms, and apply them to the cleanest data, but unless we change the way something is done then we’re not adding value. To move the needle with data science, we need to positively impact the way the business does something.

So, what is a Data Scientist?

Each part of our definition hints at a particular skill that’s needed:

  • Data: ability to manipulate data across a number of dimensions (volume, variety, velocity)
  • Advanced analytics: understanding of a range of analytic approaches
  • Proactive: communication skills that allow us to interact with the business
  • Decision making: the ability to turn analytic thinking (e.g. models) into production code so they can be embedded in systems that deliver insight or action

If data science, as a proactive pursuit, is concerned with the meeting of a range of business challenges, then a data scientist must —understand at least the possibilities— a wider range of analytic approaches.

So… we just need to hire Unicorns?

From what I’ve said earlier it sounds like you just need to hire people who understand every analytic technique, code in every language, etc.

I’ve been interviewing prospective Data Scientists for more than 15 years and I can safely say that data science ‘unicorns’ don’t exist (unless you know one, and they’re interested in a role – in which case, please contact me!).

The fact that unicorns don’t exist leads to a very important part of data science: Data Science is a Team Sport!

While we can’t hire people with all the skills required, we can hire data scientists with some of the required skills, and then create a team of complementary skillsets. This way we can create a team that, as a collective, contains all of the skills required for data science. How to successfully hire this team is whole other blog post (keep your eyes peeled)!

Do you know where you currently sit with your skills and knowledge? Take our Data Science Radar quiz to find out!

If you’re looking at building your company’s data science capabilities, the Mango team have helped organisations across a range of industries around the world build theirs. The key is having the right team and the right guidance to ensure your analytics are in line with your objectives. That’s where we come in, so contact us today: sales@mango-solutions.com