2 min read

Writing R in VSCode: Interacting with an R session

In the previous post, I introduced the features languageserver enables the code editor to provide when we are editing R scripts. But this is only part of the story. A major part of using R is about exploring data interactively, which requires some extent of interactivity between the code editor and a live R session.

The latest vscode-R implements an experimental feature called R session watcher, which makes it possible for VSCode to communicate with any live R session under a wide range of scenarios. To try it, we just need to follow the steps in project README.

To work with R more smoothly, I recommend using radian as the default R console, which has syntax highlight, auto-completion, better support of sending code chunks (bracket-paste mode), and better support of unicode characters.

My typical workflow is that I connect to a server machine via SSH using Remote Development in VSCode. And I always prefer self-managed R sessions in a tmux window for persistence. Therefore, I need the following VSCode options:

{
  "r.alwaysUseActiveTerminal": true,
  "r.bracketedPaste": true,
  "r.sessionWatcher": true
}

where r.alwaysUseActiveTerminal allows me to always send code to active terminal rather than vscode-R helps me to start an R session which is terminated when VSCode exits; r.bracketedPaste is required to work with radian to allow sending large code chunks which official R terminal cannot handle correctly.

This makes it easy to work with multiple R sessions. I only need to start a tmux session, open multiple windows, and start as many R sessions as I need in these windows. All these R sessions will be safely preserved when VSCode exits. And I can attach to the tmux session on another machine and restore everything in my need.

Another thing is that although langaugeserver supports document formatting based on styler, it is slow for large scripts. Therefore, I'd rather it is disabled with the following VSCode option and I use Format Document on demand.

{
  "[r]": {
    "editor.formatOnSave": false
  }
}

Following are some pictures to demonstrate how VSCode could interactive with a live R session.

  • Show symbol value on hover

Symbol hover

Symbol hover

  • Basic plot and ggplot2

Basic plot

ggplot2

plotly

highcharter

shiny

profvis

  • View data frame

View data frame

  • View list

View list