Chapter 51 Using your .Rprofile and .Renviron file and RStudio Code Snippets
This chapter is part of the Coding pathway.
Packages needed for this chapter include {usethis}.
These are two tools that will help you extend what you can do with R and RStudio. The .Rprofile
file is a file that is run every time you start R, and it can be used to set options, load packages, and define functions that you want to use in every R session. RStudio Code Snippets are a way to save and reuse code snippets in RStudio, which can help you work more efficiently. Let’s start with the .Rprofile
file.
51.1 Setting up your .Rprofile file
You can create a .Rprofile
file in your home directory or in any project directory. This file is run every time you start R, and it can be used to set options that you want to use in every R session.
The upside to this is that your workspace is set up consistently the same way every time you start R, and you don’t have to remember to load packages or set options every time. The downside is when you share your code with collaborators, it may not run, as they do not have the same .Rprofile
file.
In general, you should use the .Rprofile
file for things that you want to set up every time you start R, and that are not specific to a project. For example, you might want to set options for how R displays output.
However, you should avoid loading packages or functions in your .Rprofile
file, as this can cause issues when you share your code with collaborators. Instead, you should load packages in your R scripts or RMarkdown files, or use the {renv} package to manage your project-specific library paths and package versions.
The .Rprofile
file is a user-controllable file that can be located in your home directory (~/.Rprofile
) or in a project-specific directory (e.g., my_project/.Rprofile
). When you start R, it will look for a .Rprofile
file in your home directory and in the current working directory, and it will run the code in that file. This allows you to set options that you want to use in every R session. This is a ‘secret’ file that is not visible in the RStudio Files pane, but you can see it in the RStudio source pane if you open it with usethis::edit_r_profile()
. It will not be shared on Github when you push your code to a repository, as it is a hidden file (the dot at the beginning of the filename makes it hidden in Unix-like operating systems).
To set up your .Rprofile
file, you can use the {usethis} package. The following code will create a .Rprofile
file in your home directory if it does not already exist, and then open it in RStudio for editing:
This will open the .Rprofile
file in the source pane of RStudio, and you can add any code that you want to run every time you start R.
You can edit your .Rprofile
file to set some options.
Here are a few common examples of what people often do wtith their .Rprofile
file:
options(stringsAsFactors = FALSE) # Set strings to not be factors by default
options(digits = 3) # Set the number of digits to display in output
options(scipen = 999) # Set scientific notation to not be used with a high penalty
options(tab.width = 2)
options(width = 60)
options(editor = "TextEdit")
options(usethis.full_name = "Your Name Here") # Set your name for use in package development
options(usethis.protocol = "https")
# fancy quotes are annoying and lead to
# 'copy + paste' bugs / frustrations
options(useFancyQuotes = FALSE)
options(prompt = "R> ") # CUSTOM prompt
options(max.print = 400)
options(repos = c(CRAN = "https://repo.miserver.it.umich.edu/cran/"))
It is generally a bad idea to set the default library path in your .Rprofile
file, as this can cause issues when you share your code with collaborators.
Similarly, it is generally a bad idea to load packages in your .Rprofile
file, as this can cause issues when you share your code with collaborators.
Instead, you should load packages in your R scripts or RMarkdown files, or use the {renv} package to manage your project-specific library paths and package versions.
Note that to apply changes to your R session, you need to save the .Rprofile
file and then restart R. You can do this by clicking on Session/Restart R in RStudio, or by pressing Shift-Cmd-O.
51.2 Setting up your .Renviron file
You can use the .Renviron
file to store secrets that you need to use to access data through APIs (Application Programming Interfaces). APIs are a common way to make data public, but require users to present a password or key to gain access to the data. API keys are commonly used for REDCap databases, US Census data, Qualtrics data, Github, and many other websites. By storing your API keys in your .Renviron
file, these keys remain secret on your computer, and never appear in your code. This means that they will never be revealed on Github, or any other form of code sharing.
To set up your .Renviron
file, you can use the {usethis} package. The following code will create a .Renviron
file in your home directory if it does not already exist, and then open it in RStudio for editing:
This will open the .Renviron
file in the source pane of RStudio, and you can add any environment variables that you want to use in your R session.
Typically, these will look something like this:
# Example of an API key for a REDCap database
REDAPI_KEY="R4d3Fc56GGcvlr92EwTu3d4"
# Example of an API key for a US Census database
CENSUS_API_KEY="Jl45Rsw34iop83YuTiu4r5"
# Example of an API key for Mapbox mapping data
MAPBOX_API_KEY="peyJ1IjoicGV0ZXJoaWdnaW5"
You can add as many environment variables as you need, and they will be available in your R session. You can access these environment variables using the Sys.getenv()
function, and store them in a variable using code like this:
You can also use the usethis::edit_r_environ()
function to edit your .Renviron
file, adding new secret API keys, and then restart R to apply the changes.
51.2.1 Using RStudio Code Snippets
RStudio Code Snippets are a way to save and reuse snippets of code in RStudio, which can help you work more efficiently. You can create code skeletons for common tasks, such as loading packages, creating plots, or running analyses. This can save you time and reduce the amount of code you need to write.
To create a code snippet, you can use the {usethis} package. The following code will create a new code snippet file in your home directory if it does not already exist, and then open it in RStudio for editing:
Note that there are a bunch of preloaded R snippets that you can use in RStudio, and you can find them in the RStudio documentation here.
You can see the basic structure of an RStudio code snippet below:
Take for example, the fun
snippet, which is a code snippet that creates a function skeleton. You can use it by typing fun
and then pressing the Tab key. This will expand the snippet into a function skeleton that you can fill in with your own code. Open a new R script in RStudio, type fun
and then press the Tab key to see how it works.
You can probably imagine situations in which this would be helpful, just to set up the syntax and be able to fill in the blanks.
One common situation that I use code snippets for is when I am using a function (that I don’t use that often) with multiple arguments, and I (usually) end up googling all the arguments to get them right. I can avoid this by creating a code snippet that has the function name and all the arguments, so I can just fill in the values. For example, for pivot_wider, I can create a code snippet like this:
snippet pwider
pivot_wider(mydf,
id_cols = optional vector of unaffected columns,
names_from = c(category column(s) to pivot wide),
values_from = c(value column(s) that hold data for each category column),
names_sep = "_")
Try editing your snippets file to add this code snippet, save the file, and then try it out in a new R script in RStudio. Type pwider
and then press the Tab key to see how it works. You can then fill in the values for the arguments as needed.
51.3 Code Folding and Sections in RStudio
This is a minor quality of life improvement, but it can be very useful when you have long R scripts or RMarkdown files. You can use code folding to collapse sections of your code, so you can focus on the parts that you are currently working on. This can help you navigate your code more easily and reduce clutter.
To use code folding, you can add a section header to your code by using the #
symbol followed by a space and the section name.
To insert a new code section you can use the Code -> Insert Section command. Alternatively, any comment line which includes at least four trailing dashes (-), equal signs (=), or pound signs (#) automatically creates a code section. For example, all of the following lines create code sections:
# Section One ———————————
# Section Two =================================
### Section Three #############################
you can add a section header like this:
# Section Name ----------
# This is a section of code that can be collapsed
# You can add more code here
# You can also add subsections by using `##` for a subsection header, or `###` for a sub-subsection header. For example:
# ## Subsection Name ========
# # This is a subsection of code that can be collapsed
You can then collapse the section by clicking on the small triangle icon next to the section header. This will hide the code in that section, and you can click on the triangle icon again to expand it. This can help you focus on the parts of your code that you are currently working on, and reduce clutter in your R scripts or RMarkdown files.
51.3.1 Explore More
You can find out a lot more about how an R session starts up, using .Rprofile
and .Renviron
files here
There is great documentation on the {usethis} package (which can do lots of other mundane but practical things for you) here.
You can also find out more about RStudio Code Snippets here and here.
A lot of information about best practices for using R and RStudio (that are quite useful) can be found in the book What They Forgot to Teach You About R.
You can read more about sections and code folding here