CUSTOMISED
Expert-led training for your team
Dismiss
How to Run R Language in VS Code

31 August 2023

How to Run R Language in VS Code

R is a popular programming language used by data scientists and statisticians for statistical analysis and visualisation. With its vast collection of packages and simple syntax, R makes data exploration easy and intuitive.

JBI Trainings R language course is a perfect solution for training. Get in contact to find out how we can assist with your R Language Training. 

While RStudio is the go-to IDE for R development, using R in Visual Studio Code has several advantages. VS Code provides a lightweight yet powerful editor with built-in Git support, debugging, and integration with other languages like Python.

In this guide, you’ll learn how to set up R in VS Code and leverage its features for efficient R programming and analysis.

Getting Started with R in VS Code

To use R in VS Code, you'll need to install a few prerequisites first:

Install Visual Studio Code

Download VS Code for your operating system from https://code.visualstudio.com/. VS Code is available free for Windows, macOS and Linux.

Once installed, open VS Code. You'll be presented with a minimal interface consisting of a sidebar, editor pane, and command palette.

Install R

Download and install R from https://cran.r-project.org/ based on your operating system.

Make sure to install the latest version of R to get all the recent updates and packages.

Install R Extension

VS Code needs the R extension to work with R files. Search for "R" in the extensions marketplace and install the R extension by RStudio.

Once installed, you'll notice new R file icons and syntax highlighting for R files in the editor.

With these three prerequisites set up, you're ready to start using R in VS Code!

Configuring VS Code for R

While VS Code works out of the box for R, tweaking a few settings can enhance your R programming workflow:

Enable Auto Save

R files in VS Code need to be saved before executing code. Enable auto save so you don't have to manually save whenever you run code.

Go to File > Auto Save and set it to afterDelay. Your R files will now automatically save after a delay.

Install Additional R Packages

You can install R packages directly within VS Code using the command palette. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS) to open the palette and run R: Install Packages.

Search for and install popular packages like dplyr, ggplot2, tidyverse to get started.

Set Working Directory

By default, R scripts execute from the user home directory. Change this by setting the working directory in VS Code:

setwd("/path/to/working/directory")

Now R will execute scripts with this directory as the starting point.

Customise Keybindings

Programmers familiar with RStudio can replicate its shortcuts in VS Code:

{ "key": "ctrl+enter", "command": "r.runSelection", "when": "editorTextFocus && editorHasRCode" }, { "key": "ctrl+shift+enter", "command": "r.runSource", "when": "editorTextFocus && editorHasRCode" }

This maps Ctrl+Enter to run selection and Ctrl+Shift+Enter to run source/script. Refer to the VS Code Keybindings documentation for more details.

With a productive R environment set up, it's time to start coding!

Writing and Running R Code in VS Code

Let's go through the various ways to write and execute R code within VS Code:

Create a New R Script

Open a new .R file in VS Code. This will be treated as an R script.

Start writing R code in the editor - you'll get auto-completion, syntax highlighting, and other features.

Execute Code With Shortcuts

To run the current line or selection, press Ctrl+Enter. To run the entire script, use Ctrl+Shift+Enter.

These keybindings mimic RStudio for a familiar experience. You'll see the output directly inside VS Code.

Use the Integrated Terminal

The integrated terminal lets you run R code interactively. Open the terminal with Ctrl+` and type R to start an R session.

You can now run R code and see results. For example:

> x <- rnorm(100) > mean(x) [1] 0.018908

The terminal approach is great for testing code quickly without creating a file.

Source R Files

You can also source existing R scripts inside the terminal with:

> source("/path/to/script.R")

This executes the code in the script line-by-line.

Debug Code

To debug R code, set breakpoints directly in the editor by clicking on the gutter. Then launch the debugger with F5.

You can step through the code line by line inspecting variables along the way. The debugger is invaluable for catching bugs.

With the editor, terminal, and debugger, you have all the tools to productively write R code in VS Code. Next let's look at extended R support.

R Markdown and Notebooks

In addition to R scripts, you can also write R Markdown files and Jupyter notebooks in VS Code.

R Markdown

R Markdown lets you combine R code, results, and prose commentary in a single document. To create one in VS Code:

  1. Open the command palette and select R: New R Markdown File.
  2. Choose the Markdown flavor - either standard or quarto.
  3. Start editing the .Rmd file, running code chunks using Ctrl+Shift+Enter.
  4. Render the final document with Ctrl+Shift+K or the command palette.

R Markdown is great for reproducible analysis and reporting.

R Notebooks

Notebooks break up code execution into cells, helping visualize results incrementally. To use notebooks:

  1. Open the command palette and pick R: New R Notebook.
  2. Execute code cells with Ctrl+Enter and view outputs including plots.
  3. Save and export the notebook using the menu buttons.

Notebooks are an interactive way to build R analyses piece by piece.

Version Control with Git

Since R projects often span multiple scripts and files, using version control helps track changes over time.

VS Code has built-in Git support through the source control tab. You can initialize a repo, make commits, view diffs, and push to remote repositories like GitHub:

Set up version control from the start to maintain a history of your R project safely in the cloud.

Useful R Packages and Examples

To apply your R coding skills in VS Code, here are some useful packages and examples to try:

dplyr

dplyr provides a grammar of data manipulation, letting you easily subset, transform, and summarize datasets with expressions like:

library(dplyr) mtcars |> filter(cyl == 8) |> select(mpg, hp) |> summarize(mean_mpg = mean(mpg))

ggplot2

ggplot2 lets you create publication-quality graphics with a syntax designed for thinking about data visualization:

library(ggplot2) ggplot(mtcars) + geom_point(aes(x = wt, y = mpg))

Shiny

Shiny enables creating interactive web apps directly from R. You can build dashboards and data products integrating R, HTML, and JavaScript.

Conclusion

This guide covered setting up R in VS Code, customising the editor, running code in the terminal and debugger, using R Markdown notebooks, integrating with Git, and some useful R packages to learn.

With its flexibility and large ecosystem of extensions, VS Code is a great alternative to RStudio for your R programming needs. R languages offers data scientists an unrivaled environment for statistical computing and visualisation. Combining it with VS Code results in a lightweight yet powerful IDE for any R developer.

So download VS Code, install the R extension, and start coding in R today!

This guide showed how to run the R language for statistical computing in Visual Studio Code. With just a few steps, you can set up a productive environment for R programming, analysis, and visualisation using VS Code's editor, debugger, version control and markdown integration.

If you found this guide useful check out our article on how to take input in r language all part of R Language Course

Amidst the evolving landscape of modern technology, the course offerings at JBI Training cater to a wide array of interests and expertise. For those who find themselves drawn to the world of data analysis and statistical exploration. Dive deep into the capabilities of the R language, honing your skills to craft dynamic reports and interactive dashboards using the Shiny framework. Unlock the potential to transform complex data into visually engaging and informative presentations.

1. R Language: This foundational course introduces you to the core concepts of the R programming language. Learn about data structures, functions, and control flow to embark on your journey into data analysis and visualization.

2. R - Reporting & Dashboards with Shiny: Elevate your R expertise by delving into Shiny, a powerful web application framework for R. Master the art of creating interactive reports and dashboards that bring your data to life, making complex insights easily accessible.

3. R with RMarkdown and Quarto: Explore the art of reproducible reporting using RMarkdown and Quarto. Learn to create dynamic documents that blend code, analysis, and visualization, ensuring transparency and replicability in your data-driven narratives.

Enrol in these courses and unlock the full potential of the R language for data analysis, reporting, and visualization. Equip yourself with the tools and knowledge to navigate complex datasets, derive meaningful insights, and present your findings effectively.

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course