3 min read

Motivate yourself with an .Rprofile

Matt Dray (@mattdray)

Hang in there, buddy (via Giphy)

Hang in there, buddy (via Giphy)

What’s an R profile?

It’s a file that contains R code that runs when you start or restart R. You can use it to customise your environment. For example, you could set options, create functions or load packages.

There’s lots of information in the R startup chapter of Colin Gillespie’s’s Efficient R Programming book.

But beware: use of an R profile may not be particularly reproducible if the .Rprofile file is unavailable to others who are excuting your code. For example, you might use your profile to load packages that aren’t installed by another user.

You can use your favourite search engine to find examples of people’s R profiles. For example, in:

I’m going to create something a little more… fun.

How to edit your .Rprofile

You could navigate to where the .Rprofile file is stored on your machine and edit it, but it’s easier to use the edit_r_profile() function from the usethis package.

usethis::edit_r_profile()
## ● Edit '.Rprofile'
## ● Restart R for changes to take effect

The output from running this line shows the filepath to the .Rprofile and reminds you to restart R to reload the R profile and its newly-saved changes.

A frivolous use case

You could use your R profile to display a little message at startup.

It’s four days into 2019 and you may be struggling with those new year resolutions. You’re probably going to need a motivational quote.

We can load the emo package within the R profile and add emojis to our messages. There’s a handy function – emo::ji_glue() – that allows you to paste text with emojis.

The following code selects one element at random from a set of motivational messages and prints it to the console on startup.

library(emo)  # devtools::install_github("hadley/emo")

cat(
  sample(
    x = c(
      ji_glue("Don't let your dreams be dreams! :rainbow:"),
      ji_glue("Nothing is impossible! :raised_hands:"),
      ji_glue("Be brave! :triumph:"),
      ji_glue("Do the thing! Yeah! :white_check_mark:"),
      ji_glue("Haters gon' hate! :tipping_hand_woman:"),
      ji_glue("Crush your enemies! :fist:"),
      ji_glue("Generic motivational quote! :clap:")
    ),
    size = 1
  )
)

You need a blank line at the end of the file. One will be added for you on save when editing in RStudio.

Outcome

Here’s the code in the script window and the result of having restarted R a few times.

Random messages selected from the .Rprofile on restart

Random messages selected from the .Rprofile on restart

Just don’t get stuck in a loop of restarting R over and over again so you can see the messages. You might get overmotivated. Or you’ll spend so long restarting that you’ll have wasted loads of time and will need more motivational quotes to encourage yourself not to do it anymore.