6  Interactive R Programming in VSCode

Keywords

interactive R programming, R in VSCode, run R code in VSCode, R terminal in VSCode, httpgd in VSCode

6.1 Introduction

VSCode provides an interactive and flexible environment for running R scripts and exploring data.

In this chapter, we’ll explore the various ways you can leverage VSCode for interactive R programming, focusing on running code interactively and exploring results in real-time.



6.2 R Terminal Integration

VSCode allows you to interactively run R code in several ways, making it convenient for testing and exploring your scripts.

  • Open an R Terminal: To start an R terminal session in VSCode, use the command palette (Ctrl + Shift + P or Cmd + Shift + P), then select R: Create R terminal. This will open a terminal session where you can execute R commands interactively. By default, the standard R console will open.

    Standard R Terminal

    We suggest using radian for an improved R console experience. Radian enhances the experience with features like syntax highlighting, auto-completion, and better handling of code chunks.

    Radian R Terminal
  • Auto-Attach to Active Terminal: If the R session watcher is active, it will connect to the R session as soon as a new R terminal is created. The session watcher status is displayed in the status bar.

    Session Watcher Status
  • Run Selected Code: Highlight a line or block of code and press Ctrl + Enter (Windows/Linux) or Cmd + Enter (Mac) to send the selected code to the R terminal for immediate execution.

  • Run Line-by-Line: Place your cursor on a line and press Ctrl + Enter or Cmd + Enter. This allows you to execute each line as you progress through the code, ideal for debugging or testing.

6.3 Running R Code Interactively

The vscode-R extension integrates with the R terminal, providing a seamless interface for sending code directly to the terminal.

  • Open an R Terminal: To start an R terminal session in VSCode, use the command palette (Ctrl + Shift + P or Cmd + Shift + P), then select R: Create R terminal. This will open a terminal session where you can execute R commands interactively. By default, the standard R console will open.

    We suggest using radian for an improved R console experience. Radian enhances the experience with features like syntax highlighting, auto-completion, and better handling of code chunks.

  • Auto-Attach to Active Terminal: If the R session watcher is active, it will connect to the R session as soon as a new R terminal is created. The session watcher status is displayed in the status bar.

6.4 Using Self-Managed R Terminals

Self-managed R terminals are useful when you need to maintain R sessions after closing VSCode. On Linux and macOS, tools like screen and tmux can help keep R sessions and other terminal programs active.

  • Using screen or tmux: These tools allow you to run persistent terminal sessions that remain active even if you close your VSCode window or disconnect from the server. This is particularly useful for running long computations.

  • Start an R Session in tmux: Open a terminal and type tmux to start a new session. Then start R (or radian) as usual. You can detach from the tmux session by pressing Ctrl + B followed by D, and reattach later by typing tmux attach.

  • Configuration for Self-Managed Terminals: To have self-managed R terminals behave like VSCode-managed ones, add the following to your ~/.Rprofile:

    if (interactive() && Sys.getenv("RSTUDIO") == "") {
      Sys.setenv(TERM_PROGRAM = "vscode")
      source(file.path(Sys.getenv(
        if (.Platform$OS.type == "windows") "USERPROFILE" else "HOME"
      ), ".vscode-R", "init.R"))
    }

    After adding this, starting an R terminal will signal the session watcher to attach to the R session.

6.5 Interactive Plots and Visualization

6.5.1 Viewing Plots with httpgd

The httpgd package provides an excellent way to view your plots interactively within VSCode. It creates a graphics device that serves plots via HTTP, which can be viewed directly in VSCode.

  • Enable Plot Viewer: Install httpgd in R with install.packages('httpgd'), and enable it in VSCode by setting 'r.plot.useHttpgd': true in your settings.json file.

  • Interacting with Plots: When using httpgd, any plot commands you execute will update in the VSCode plot viewer, giving you an interactive way to explore and refine your visualizations.

    Plot viewer

6.5.2 Using the Plot Viewer

The built-in plot viewer in VSCode makes it easy to interact with your visualizations.

  • You can zoom in, export, or even copy images from the viewer.
  • Simply click on the plot in the viewer pane to interact with it, offering an enhanced experience for data exploration.

6.6 Using R Markdown for Reproducible Analysis

R Markdown provides a convenient way to combine code, output, and commentary in one place. VSCode, with the vscode-R extension, offers full support for running and previewing R Markdown documents.

  • Running Code Chunks: Use Ctrl + Alt + Enter (Windows/Linux) or Cmd + Option + Enter (Mac) to run individual code chunks within an R Markdown file.
  • Previewing Output: You can preview the output in the VSCode viewer, or render the entire document by running rmarkdown::render('your_file.Rmd') in the terminal.

6.7 Debugging and Exploring Data

VSCode’s interactive features make debugging and data exploration more intuitive.

6.7.1 Debugging Tools

  • Setting Breakpoints: You can set breakpoints in your R scripts by clicking in the left margin of the editor, making it easy to pause execution and inspect variables.
  • Using vscDebugger: Install the vscDebugger package and the corresponding VSCode extension (vscode-R-debugger) to enable full debugging capabilities, such as stepping through code, inspecting variables, and evaluating expressions during runtime. See Chapter Chapter 2 for setting up Vscode for R programming.

6.7.3 Workspace Viewer

The workspace viewer displays information about the objects in the global environment of the attached R session.

  • View or Remove Objects: You can view objects by sending View(obj) to the terminal or remove them by sending rm(...) to the terminal.

  • Nested Structures: To show the second level of nested structures, such as list elements or data frame columns, you can add the following option:

    options(vsc.str.max.level = 2)

    Workspace Viewer

6.7.4 Help Pages Viewer

The help pages viewer lists several options to work with help pages, topics, and packages.

Help Pages Viewer

6.7.5 Package Management

In the help pages viewer, you can install and remove packages. Pressing any key will trigger the search mode so that you can easily find a package by name.

Help pages viewer provides an easy way to access help pages, install/remove packages, and navigate through package documentation.

6.8 Conclusion

Mastering interactive R programming in VSCode significantly enhances your productivity, especially when it comes to data exploration and real-time visualization. Whether you’re running R scripts in a standard or self-managed terminal, exploring datasets, visualizing plots interactively, or managing packages from the VSCode sidebar, this integrated workflow empowers you to be more effective as a data scientist or developer. The combination of VSCode, the vscode-R extension, and tools like httpgd and radian provide a feature-rich environment for seamless R programming.