10 Useful R Features You Might Not Know About

10 Useful R Features You Might Not Know About

R is full of various functions. Below I will list ten of the most interesting of them, which many might not know about. The article came about after I discovered that my stories about some of the features of R that I use in my work are enthusiastically received by familiar programmers. If you already know everything about this, then I apologize for wasting time. At the same time, if you have something to share - advise something useful in the comments.

Skillbox recommends: Practical course "Python developer".

We remind you: for all readers of "Habr" - a discount of 10 rubles when enrolling in any Skillbox course using the "Habr" promotional code.

switch function

I really, really like switch(). In fact, this is a convenient shorthand for the if statement when choosing a value according to the value of another variable. I find this especially useful when I'm writing code that needs to load a specific set of data according to a previous selection. For example, if you have a variable named animal and you want to select a specific set of data depending on whether the animal is a dog, cat, or rabbit, write this:

data<-read.csv(
switch(animal,
"dog" = "dogdata.csv",
"cat" = "catdata.csv",
"rabbit" = "rabbitdata.csv")
)

This feature is useful in Shiny applications where different datasets or environment files need to be loaded depending on one or more input menu items.

Hotkeys for RStudio

This hack is not so much for R, but for RStudio IDE. Nevertheless, hotkeys are always very convenient, allowing you to save time when entering text. My favorites are Ctrl+Shift+M for the %>% operator and Alt+- for the <- operator.

To view all hotkeys, just press Alt+Shift+K in RStudio.

flexdashboard package

When it comes to getting your Shiny dashboard up and running quickly, nothing beats the dashboard package. It provides the ability to work with HTML labels, which in turn allow you to create sidebars, rows and columns easily and without problems. There is also the ability to use the title bar, which allows you to place it on different pages of the application, leave icons, labels on Github, email addresses and much more.

The package allows you to work within Rmarkdown, so you can put all applications in one Rmd file, rather than distributing them across different servers and UI files, as is done, for example, using shinydashboard. I use flexdashboard whenever I need to prototype a simple dashboard before starting to work on something complex. This feature allows you to create a prototype within an hour.

req and validate functions in R Shiny

Developing in R Shiny can be confusing, especially when you keep getting weird error messages that make it hard to figure out what's going on. But over time, Shiny develops and improves, more and more functions appear here that allow you to understand the cause of the error. So, req() solves the problem with a "silent" error, when it is not at all clear what is wrong. With it, you can display user interface elements related to previous actions. Let's explain with an example:

output$go_button <- shiny::renderUI({

# only display button if an animal input has been chosen

shiny::req(input$animal)

# display button

shiny::actionButton("go",
paste("Conduct", input$animal, "analysis!")
)
})

validate() checks everything before rendering and gives you the option to display an error message, such as that the user has uploaded the wrong file:

# get csv input file

inFile <- input$file1
data <-inFile$datapath

# render table only if it is dogs

shiny::renderTable({
# check that it is the dog file, not cats or rabbits
shiny::validate(
need("Dog Name" %in% colnames(data)),
"Dog Name column not found - did you load the right file?"
)

date
})

More information about all these features can be found here.

Storing your credentials for yourself in the system environment

If you plan to share code where you need to enter access data, use the system environment in order to avoid posting your own credentials in Github or another service. Placement example:

Sys.setenv(
dsn="database_name",
UID = "UserID",
PASS="Password"
)

Now you can login using environment variables:

db <- DBI::dbConnect(
drv = odbc::odbc(),
dsn = Sys.getenv("DSN"),
uid = Sys.getenv("UID"),
pwd = Sys.getenv("PASS")
)

Even more convenient (especially if you use the data frequently) is to set it as an environment variable directly in the operating system. In this case, they will always be available and you won't have to specify them in the code.

Automate tidyverse with styler

To clean up the code, the styler package can help, which has a lot of features for automatically bringing code style to tidyverse. All you need to do is run styler::style_file() on your problematic script. The package will do a lot (but not all) to clean up the mess.

Parameterizing R Markdown Documents

So, you've created a great R Markdown document in which you analyze various facts about dogs. And then it occurs to you that it would be better to do the same work, but only with cats. No problem, you can automate cat reporting with just one command. All you need to do is parameterize your R markdown document.

You can do this by setting options for the YAML header in the specified document, and then setting the value options.

title: "Animal Analysis"
author: "Keith McNulty"
date: "21 March 2019"
output:
html_document:
code_folding: "hide"
params:
animal_name:
value: dog
options:
dog
β€” cat
β€” Rabbit
years_of_study:
input: slider
min: 2000
max: 2019
step: 1
round: 1
sep: "
value: [2010, 2017] -

Now you can write all the variables in the document code as params$animal_name and params$years_of_study. Then we'll use the Knit (or knit_with_parameters()) drop down menu and we'll be able to select parameters.

10 Useful R Features You Might Not Know About

revealjs

revealjs is a package that allows you to create great HTML presentations with built-in R-code, intuitive navigation and slide menus. HTML shortcuts allow you to quickly create a nested slide structure with different styles. Well, HTML will run on any device, so the presentation can be opened on every phone, tablet or laptop. Information disclosure can be configured by installing a package and calling it in a YAML header. Here is an example:

title: "Exporing the Edge of the People Analytics Universe"
author: "Keith McNulty"
output:
revealjs::revealjs_presentation:
center:yes
template:starwars.html
theme: black
date: "HR Analytics Meetup London - March 18, 2019"
resource_files:
β€” darth.png
- deathstar.png
- hanchewy.png
β€” millennium.png
- r2d2-threepio.png
-starwars.html
β€”starwars.png
β€”stormtrooper.png
β€”

Presentation source code posted here, and herselfrpubs.com/keithmcnulty/hr_meetup_london'>presentation is here.

10 Useful R Features You Might Not Know About

HTML tags in R Shiny

Most programmers don't take full advantage of the HTML tags that R Shiny has. But it's only 110 tags that make it possible to create a short call for an HTML function or media playback. For example, I recently used tags$audio to play a "victory" sound that alerted the user when a task was completed.

praise package

Using this package is very simple, but you need it to display praise to the user. It seems strange, but they actually like it.

10 Useful R Features You Might Not Know About

Skillbox recommends:

Source: habr.com

Add a comment