How to run R in Visual Studio Code

If you’re a happy RStudio user like me, you may never have felt the urge to try another editor for R (or even Python). But if you want the best experience when using GitHub Copilot generative AI, especially Copilot Chat, it’s worth giving Visual Studio Code a try to compare. While Copilot is available in the RStudio IDE and you can ask questions of it by prefixing your queries with # q, I find the new Copilot Chat interface in VS Code is more helpful. Copilot Chat came out of beta at the end of December 2023.

Set up Visual Studio Code for R

Unfortunately, setting up Visual Studio Code to work with R isn’t quite as easy as installing RStudio. That’s because VSCode has the capacity to support hundreds of programming languages, whereas RStudio is more focused. Offering all VS Code’s language capabilities out of the box would make for a bloated piece of software. Instead, the IDE takes a modular approach, and most users have to install extensions in order to optimize it for their specific use cases.

R users will need to install a couple of extensions and tweak a few settings.

Step one, obviously, is downloading Visual Studio Code, which you can find on the Visual Studio Code website (choose Visual Studio Code instead of Visual Studio 2022). VS Code is free and available for Windows, Mac, and Linux. Install it like any other software package.

Next comes adding R support. On the left “activity” navigation bar in Visual Studio Code, click the icon with the four squares to search for extensions. I searched for “R language” because a search for “R” will return oodles of non-relevant results. Select R by REditorSupport, which will likely show up as your first search result, as shown here.

The R extension for VS Code installation screen Screenshot by Sharon Machlis for IDG

Click the extensions icon to search for R Language extensions.

Once you click the Install button, you should see a screen with information about how to configure and run the extension. Take note of this information, as you will need it later.

Instructions for configuring the R extension for VS Code Screenshot by Sharon Machlis for IDG

Once you’ve installed the extension, you should see a screen with details about how to optimize and use it.

I also read the REditorSupport wiki page, GitHub wiki page for using R in VS Code, and the main GitHub page for REditorSupport to see what else I might want to add or change to improve my R experience.

One of the first suggestions is to use the radian terminal. That’s not a VS Code extension but an application written in Python—which means your system needs Python installed in order for radian to run. I already have Python and the conda package manager installed on my Mac, so I used the following installation command for radian:

conda install -c conda-forge radian

There is also a pip install command for those who use the popular Python package manager:

pip install -U radian

If you don’t have Python already installed on your system, see the How to set up VS Code for R video tutorial for easy instructions on how to install Python for use with R and RStudio.

There are a few other recommended installations for the extension:

  • languageserver
  • httpgd
  • VSCode-R-Debugger

If you use Quarto, also add the Quarto extension. There’s also a ShinyUiEditor extension with a graphical user interface to help build a Shiny R app UI if that’s of interest.

The languageserver and httpgd extensions are  R packages, so you can go back to RStudio or an R terminal and install them the usual way, with install.packages("languageserver") and install.packages(“httpgd”). Note that you may also need to install RTools, which is a Windows application and not an R package. This will let you run languageserver on Windows.

To install the VS Code R debugger, Quarto extension, and/or ShinyUiEditor, you can either go back to VS Code and install them from the VS Code extensions marketplace or click the Install button on each extension’s webpage.

Tweak Visual Studio Code settings for R

There are a variety of settings you can customize for your VS Code R experience, such as how much of an object to view when hovering and if you want to use the httpgd plot viewer instead of the VS Code default. You can see a list of settings on the REditorSupport extension’s settings page.

The easiest way to change a VS Code setting is to open up settings in the user interface. Another other option is editing the settings JSON file. To get to the settings UI, go to either File > Preferences > Settings on Windows or Code > Settings > Settings on Mac. You can then search for bracketedPaste and click to enable it.

You can also get to the settings UI using VS Code’s command palette. The command palette is a handy way of accessing all sorts of VS Code capabilities by typing instead of pointing and clicking at menus. Many software development environments have command palettes (including RStudio), and they’re good to get to know. In VS Code, you can pull up the command palette either with the F1 key or the key combination Control-Shift-P on Windows or Command-Shift-P on Mac.

Screen shot shows searching for 'open settings' in the VSCode command palette. Screenshot by Sharon Machlis for IDG

You can use the command palette to access VS Code settings options.

Once you’ve opened the command palette, you can use it to get to VS Code settings by typing Open Settings. You should see a choice to open the graphical UI or the underlying JSON file.

In the GUI, you can scroll down to see a list of extensions and then click on R, where you’ll get a list of choices for your R extension. The R Debugger also has a list of customizations.

If you want to use the recommended radian terminal, you’ll need to set that in the options by adding the path to radian in the R > Rterm setting for your operating system. On my Mac, I found radian in /Users/smachlis/.pyenv/shims/radian, but your location may be different.

For some of the possible customizations, it might be easier to go into the JSON file and add options manually.

All of this is a bit more complicated to set up than the one-and-done RStudio installation. It is similar to first installing R, which is often followed by installing a lot of packages like tidyverse, data.table, and janitor on top of your brand new basic R installation.

Write and run R code in VS Code

It’s common in VS Code to open a folder when working in R, and not simply create a new file. You can open a folder by going to File > Add Folder to Workspace if you’d like a setup similar to RStudio projects. Otherwise, all you have to do is open the folder. Once you do that, you can use the “explorer” icon at the top of the left-side activity navigation bar to view available files.

You can run a line of code or several lines you’ve selected by hitting Control-Enter on Windows or Command-Enter on Mac. That’s pretty similar to RStudio.

If you click the R icon on the left-most navigation bar, you’ll see information about what packages and objects are loaded into your workspace. There is an option to view a data frame or other object if you hover over the variable name and click the view icon at the right. You can also use the View() function in the terminal, such as View(mtcars). The view is searchable and filterable, although not quite as elegant as what RStudio provides. Using the help() or ? help shortcut will bring up an HTML version of a function’s help file, an improvement from several years ago when VS Code displayed the help in a Unix-like text format.

Screen shot of help file information that pops up for gemo_bar upon mouse hover Screenshot by Sharon Machlis for IDG

Hover your mouse over a function such as ggplot2’s geom_bar() and VS Code will return help file info.

If you hover over a function, you’ll get some help information without having to type anything, which is convenient.

The hover works for variables you define, too.

You can preview R graphics in VS Code by running graphics code in a package such as ggplot2. The resulting graphics will pop up in a new window.

Screen shot of a color picker that pops up when mouse hovers over color hex code. Screenshot by Sharon Machlis for IDG

Use a color name or hex code in your R script, and VS Code will show a small box with that color. Click in the box and it turns into a color picker.

VS Code also has a cool R dataviz feature: When you include a color’s name or hex code in your R code, a little box pops up showing that color—and that box also serves as a color picker. Click on it and you can pick any other color, and the new color hex code will replace the old one in your code.

R code snippets in VS Code

One last thing to note is that you can’t use a code editor without code snippets. Snippets are stored code blocks that are easy to reuse by typing the snippet’s abbreviation. Some R snippets are included with the vscode-R extensions, but you can also create your own.

The first time I went to File > Preferences > Configure User Snippets on Windows (Code > Settings > Configure User Snippets on Mac) and chose R, an R snippets JSON file was automatically generated. After that, Configure User Snippets opened the r.json snippets file and let me edit my old snippets or add new ones.

Here’s the syntax for creating a snippet in VS Code:

"Snippet Title": {
 	"prefix": "what_i_type_to_trigger_snippet",
 	"body": [
 		"my R code here;",
 		"myfun(${1:argument_label} #example code"
 	"description": "Optional description for my snippet"

And below is an example of my snippet for creating a basic ggplot2 bar chart with blue bars:

"Basic bar plot blue": {
	"prefix": "myg_barplot_blue",
	"body": [
		"ggplot(${1:mydata}, aes(x = ${2:myxcol}, y = ${3:myycol})) +",
           "geom_col(color="black", fill="#0072B2")"
	"description": "Basic ggplot bar plot with blue bars outlined in black"

The dollar sign braces are variables that can be easily filled in using tabs.

RStudio has code snippets as well. Both code editors let you see available snippets when starting to type the snippet abbreviations (which is why I came up with the convention to start all my ggplot2 snippets with “myg_“). However, VS Code also lets you see a complete list of your snippets using the Insert Snippet command from the command palette—just hit the F1 key and then type “Insert Snippet” and click on that option.

Why should you use Visual Studio Code for R?

Visual Studio Code has some very useful features, and it might be worth using for certain code-heavy projects where the function and variable pop-ups would come in handy. Personally, I use it when I’m mixing R with other languages, or if I want the best possible GitHub Copilot experience.

I love the ability in VS Code to look at all my snippets, including titles and optional descriptions! That’s one feature I’d like to see in RStudio.

Still, I’ll likely stick with RStudio for most R-specific tasks where I don’t expect to need much Copilot advice. That could change as I get more comfortable with VS Code’s R environment, and as the REditorSupport extension continues to evolve.

For more R tips, head to the  InfoWorld Do More With R page.

Copyright © 2024 IDG Communications, Inc.

Source link