Whether you’re just starting your journey to developing a successful app or riding a wave of adoption, it’s a good idea to build durable R code. Projects that are built with durable code are built to adapt. Having well-thought-out coding practices in place doesn’t prevent the challenges of growing pains, but it can certainly make resolving them a lot easier.
Users add new insights to projects, exposing blind spots and ideas either missed by devs or placed on hold for priority management. Of course, hindsight is 20/20, but if you can start the development process with a strong foundation of durable code, the more likely your project will endure and be easier to update.
Build, style, and scale your Shiny application with Appsilon’s Shiny Masterclass
In this blog, we’ll take you through some best practices you should consider for building durable R code.
Video Presentation: Best Practices for Durable R Code
Code encapsulation is taking code, breaking it down into pieces, and putting them into separate modules. To put it simply, it’s bundling variables and methods as a single unit. This is a great method for organizing code, making it easier for devs to find and easily modify when needed. In general, it reduces the repetition of information by following the DRY principle.
Don’t let UX design be an afterthought. Learn how to design dashboards that people love.
There are several ways to encapsulate R code, but for this blog, we’ll stick to three of our favorites:
- Shiny modules – a pairing of UI and server, embedded into Shiny. You can use it wherever you have repeatable Shiny elements.
- Box – a package for organizing and modularizing source code for easy use across projects. Best when you have repeatable code.
- R6 classes – an implementation of OOP for R and slightly more complicated than the other methods described. R6 classes are efficient ways to place single-use objects with related logic while supporting public and private methods.
To use Shiny modules, you’ll first need to write UI and server functions. For the UI create an ID and initiate a namespace. This will consist of UI code that you write in your Shiny app using the ID from that namespace. Similarly, in the server, initiate the namespace and write standard server code with IDs from that namespace.
Speed up production with Appsilon’s open-source Shiny dashboard templates.
Once you have those two functions, you need to embed them in the shiny app. To do this, go to the UI of your Shiny app, and use the UI function directly with the unique ID. In the server, use the core module function that provides the server function you just wrote and the id to match with your UI and any additional arguments if your server function requires them.
Box is helpful when reusing functions across an application. Any extracted R files or project folders can be set as reusable modules and nested. Use is straightforward. Simply write your usual code, add
#' @export, and import the modules or packages with
In the example below, we’ll first import dependencies using the ‘box way’:
Next, if we want to reuse the module, we’ll need to import the function. Again, using the ‘box way.’ And when you want to use the function, simply call and use it.
Note: if you try to access any internal functions that were not exported, you will receive an error as they cannot be used outside the module.
R6 classes are a bit more complicated than the previous methods, but well-developed documentation can be found in Hadley’s Advanced R.
The definition of the class car is found below:
In each class, there are fields and methods. Fields are similar to variables and methods are similar to functions. And both can be listed as private or public (private meaning availability only within the class).
To generate an object in the class we will make use of the
$newfunction and then initialize.
Tests – checking for durable R code
Tests are so important and if you’re not implementing them in your development process, chances are you’re missing improvements to your application or bugs that lead to wrong results. Testing can help a project in many facets of development from ensuring the highest quality of output to maximizing cost- and time-efficiency, as well as making debugging easier. No matter the project, we always recommend making good use of various types of testing.
Are your user tests effective? Build better Shiny apps with effective user testing.
Unit testing with testthat
We recommend testthat for testing your code. It can be easily integrated into existing workflows and makes for an engaging method for testing.
In the example below, we will start with a function to test.
Then we create a file with the test, where we can describe the expected outcomes of the function in the
Two quick tips for those who are new to unit testing:
- Make sure you’re unit tests are limited to one function
- Make sure you select varying data for different use cases
One particularly useful method of testing is user interviews. Interviews can often be underappreciated or undervalued by developers, but they play a valuable role in good app development. User interviews allow you the chance to discover conceptual debt you may have in your app. No one knows your project better than you, but you might be so wrapped up in the dev and design that some things aren’t as logical to others as they are to you. This is your opportunity to check that your app is intuitive as a whole or if specific components are understandable and make sense.
We recommend following a few Golden rules for interviews, but this is by no means an exhaustive list:
- Keep it 1-on-1
- Make it the first contact with the app
- Prepare your script in advance
- Explain the specific goal(s) to the user
- Ask business questions to make them solve specific tasks
- Don’t help the user to accomplish tasks by leading them (no matter how tempting)
And as a general note, be sure that the user understands that you are not testing them, but rather the application. A user interview is a test of an app’s functionality, not a user’s abilities.
Is your Shiny app experiencing growing pains? Gain valuable performance insights by learning how to pull Shiny usage data from RStudio Connect.
Taking the time to establish a good project structure enables you to build a well-organized project for you, your team, and others to easily cooperate. It ensures that everyone knows where files are stored and how to manage them, which in turn leads to faster development. No matter the size of the project, new team members should be able to locate and contribute as quickly as possible without additional training.
Every project is unique in its setup and requirements. A project’s structure should be treated as a function of how to best serve the end goal and not be the end-all-be-all. That being said, there are a few common points to consider.
- A project’s README.md should be maintained and updated often. It should exist throughout the entire life of the project.
- Store your Shiny modules and R6 classes under modules in the app catalog. And of course, use descriptive names and group-related modules together.
- In the utils catalog, you’ll likely need more structure to group pieces of code such as helper functions that will be imported in modules or global files using the Box package
- Tests (oh yes!) catalog at Appsilon usually includes a lintr.R to check our code style is being adhered to and additional tests such as testthat, where we store the files that run unit tests.
Watch, learn, and build durable R code
Appsilon prides itself on serving the data science and R community. We’ve spent years building workflows, data science solutions, and Shiny applications for Fortune 500 companies. Along the way, we’ve developed several open source packages and free-to-download Shiny dashboard templates. We want to make sure R users have everything they need to improve their data science applications.
But we also understand that it can be challenging to build enterprise-level applications in R and Shiny. Our team of expert R/Shiny developers, software engineers, UX designers, and business analysts can tackle the most challenging data science problems and do it quickly. If you need help with your enterprise application, reach out to us. We love finding solutions to unique data science problems.