R in 2021 with VSCode

R in 2021 with VSCode

I first installed VSCode in october 2020 when I’ve decided to learn Python. Looking for the ideal setup, I’ve read somewhere that Spyder would be the best IDE for R (R Core Team 2020) users due to similarities with RStudio, but I wanted the same experience as a native Python user so I’ve decided to go with VSCode (even if that meant a tougher xp at the time).

I quickly fell in love with it’s flexibility and maturity. There are community extensions for about everything, which makes ux delightful! However, R ecosystem was still very much geared towards RStudio and I still found myself stuck with that IDE in my day-to-day life with R. That changed, of course, when I saw this tweet from Miles McBain:

Moving on to consider VSCode as a real possibility for R, I found this post from Kun Ren that offers a setup for R with VSCode. In this post I write about my favorite features and what settings that I use.

WHAT’S SO GOOD ABOUT IT THO 🤔?

Most features implemented by R and Language Server extensions are detailed in Kun Ren’s post, so, if you didn’t read that yet, just GO! Here’s some stuff I like about it.

Intellisense

That’s what is called VSCode’s code editing features, like quick info (docs for functions, datasets etc) and parameter info (args definition), just by hovering over it. It also includes code completion, member list and more.

code completion, hover, quick info, parameter info

color selection via IDE (。◕‿◕。)

Git & GitHub integration

GitHub Pull Requests and Issues and Git Lens extensions provide a very useful GitHub integration, so you don’t have to leave your IDE for nothing. You can open, comment and close issues and PRs; submit, view and edit commits; execute most common bash commands via command pallet (push, pull, checkout, prune, rebase etc) and other stuff.

new issue

Clicking on the issue, VSCode opens a new branch and checks it out for you to work on (and still triggers a personalized commit message!).

new branch via issue

And, at the end of the work, just click on create new PR to push the branch to origin and bring the PR interface. All without opening the browser or a terminal.

new pull request

Multiple terminals

While your blog or Shiny app is rendering and consequently occupying one terminal, you can simply open another one and continue working normally!

you can open as many terminals as you wish!

Draw.io

This is an example of one of the many useful extensions that the community makes available on VSCode. The draw.io extension integrates diagrams.net into VSCode. With it, you can make diagrams very quickly and without having to leave your IDE!

to bring the extension interface, just create a .drawio file

diagram I made for this post using it

Live Share

Ever dreamed of working on the same script with your boys live? The Live Share extension allows it and also provides chat and audio channels, which makes it unnecessary to open an audio call on another app while you work!

pretty much everyone right now

Also, you don’t need to have the language interpreter installed to join the session. That means that even if you’re on another machine that doesn’t have R or Python (or else) installed, you can log in and collaborate on your colleagues’ scripts, even running the code through their terminals!

two machines visualizing each other during a VSCode Live Share session

Windows Subsystem for Linux

Are you in a Windows machine and and ever needed to debug some stuff in a Linux environment? Then you had the displeasure of installing virtual machines or dual boot (╯°□°)╯︵ ┻━┻

Good news: with the Remote - WSL extension you’re just one click away from happiness. It copies your folder (project) and reopens it in a Linux environment, with a terminal ready for business!

starting a Linux session

Linter

R extension integrates the {lintr} package into the IDE, so you have real time styling updates.

real time checks

SETTINGS

To get started you only need VSCode and R and R-LSP extensions. But here I share the setup that I think provides the best experience:

  1. Visual Studio Code and extensions:
  1. Packages:
  1. Python & Radian:
  • Python (recommended): requirement for Radian, implemented in Python
  • Radian (recommended): alternative R console, with multi line editing and rich syntax highlighting
  1. Pandoc: Universal document converter, responsible for converting R Markdown (.Rmd) files to html. You didn’t need to install it before because the RStudio installer comes with a version of Pandoc included.

FIRST STEPS

With VSCode installed, you’ll see the welcome screen, which looks like this:

welcome screen

The first thing to note is that the RStudio project concept (.Rproj) does not exist in VSCode. You have a folder and that’s it, all relative paths point to it. Folder-specific settings can be defined in a .json file in the directory.

In the sidebar, the explorer tab will give you the option to open a folder (a project) or clone a repository. Opening my Advent of Code 2020 folder, you will see my directories and files on the left. There is code in Python and in R. I can open it and organize it any way I want. The terminals are below and they can also be moved elsewhere.

fully flexible editor

Extensions can be installed from the tab on the left. VSCode itself will recommend installing extensions when you open some kind of file that doesn’t have an interpreter or formatter installed, for example.

community extensions

Important: do not install the RTools extension together with the extensions mentioned above, as they are not complementary and will cause conflicts.

With the extensions installed, let’s go to settings. First, open the command palette with ctrl+shift+p. There you’ll be able to access several commands and shortcuts in VSCode, such as:

  • new terminal (R, Python etc)
  • launch RStudio addins
  • compile RMarkdown files (knit .Rmd)
  • access settings and shortcut keys
  • install packages
  • format files and MANY others

Accessing the VSCode settings, we can configure both the editor and its extensions:

settings.json

Here are the ones I currently use. Change as needed and according to your preference. Obs.: by the time you’re reading this they may be changed, since R support is on active development.

 1{
 2    // VSCode setup
 3    "terminal.integrated.shell.windows": "C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe",
 4    "editor.formatOnPaste": true, // recommended
 5    "editor.formatOnType": true, // recommended
 6    "diffEditor.ignoreTrimWhitespace": false,
 7    "files.autoSave": "off",
 8
 9    // Python setup
10    "python.pythonPath": "C:\...\anaconda3\python.exe",
11    "jupyter.alwaysTrustNotebooks": true,
12
13    // R setup
14    "[r]": { // required
15        "editor.defaultFormatter": "REditorSupport.r-lsp"
16    },
17    "files.associations": { // required
18        "*.rmd": "markdown",
19        "*.Rmd": "rmd"
20    },
21    "r.sessionWatcher": true, // default
22    "r.bracketedPaste": true, // required
23    "r.rterm.windows": "C:\...\anaconda3\Scripts\radian.exe", // for Radian
24    "r.rpath.windows": "C:\...\R\R-4.1.0\bin\R.exe", // required
25    "r.lsp.debug": true, // required
26    "r.alwaysUseActiveTerminal": true, // required
27    "r.rtermSendDelay": 0,
28}

And a few tweaks on your .Rprofile:

 1# options
 2options(
 3  # activate RStudio Addins on command pallet
 4  vsc.rstudioapi = TRUE,
 5  # interactive plots with {httpgd}
 6  vsc.use_httpgd = TRUE,
 7  # radian highlight scheme (choose what suits you)
 8  radian.color_scheme = "native",
 9  # code completion triggers
10  languageserver.server_capabilities = list(
11    signatureHelpProvider = list(triggerCharacters = list("(", ",", "$")),
12    completionProvider = list(
13      resolveProvider = TRUE, triggerCharacters = list(".", ":", "$")
14    )
15  )
16)

Important: not installing {httpgd} or not including this setting in .Rprofile will cause your graphics to be plotted in a fixed-size window, without the possibility of manipulating the plot size interactively.

AT LAST

And that’s it for the basics! There’s still a lot of things to explore but you can already get an idea of the tool’s potential :p

CITATION

For attribution, please cite this work as:

Alberson Miranda. Jun 1, 2021. "R in 2021 with VSCode". https://datamares.netlify.app/en/post/r-vscode/.

BibTex citation:

  @misc{datamares,
    title = {R in 2021 with VSCode},
    author = {Alberson Miranda},
    year = {2021},
    url = {https://datamares.netlify.app/en/post/r-vscode/}
  }

REFERENCES

Lai, Randy. 2020. Languageserver: Language Server Protocol. https://CRAN.R-project.org/package=languageserver.
R Core Team. 2020. R: A Language and Environment for Statistical Computing. Vienna, Austria: R Foundation for Statistical Computing. https://www.R-project.org/.
Rupprecht, Florian. 2021. Httpgd: A ’HTTP’ Server Graphics Device. https://CRAN.R-project.org/package=httpgd.

  1. now integrated in vscode-R extension.↩︎

comments powered by Disqus

Translations: