Using R through Positron

Overview

This unit covers the use of R inside of Positron.

Goals

  • Know how to run R code from within Positron.
  • Be familiar with Positron features that help with R coding.

Reading

Positron and Projects

As a quick reminder, for any project for which you write code, you always want to work inside a workspace with Positron. If needed, (re)visit the Positron Projects unit in the Brief Introduction to Positron course to refresh your memory about workspaces and projects in Positron.

Writing R Code in Positron

Once you have your workspace/project open, you can start creating R code. Code should be saved in and run from files. It is personal choice as to how many and what kind of files you create. In general, this will be a mix of functions and scripts (which we’ll cover briefly later).

Start a new R file by going to File -> New File -> R File. An empty file should open in the editor area. This is the area for you to write your code.

Let’s try a few lines of code, for instance type this into the editor window:

# This is a test script
x <- seq(1,100) #create a sequence from 1 to 100 and save as x
y <- x^2 #compute the square of x, assign it to y
plot(x,y) #plot y versus x

Note that you should always add a lot of explanation as comments (any text after a # sign in R) to your code. Comments are being ignored by R, but are very useful for others and your future self in understanding what’s going on in your code.

Running R Code in Positron

R gives you two main options for running code. One is interactively, line by line. That is useful for quick testing and exploring. The other option is to fully run scripts. This is the preferred way for any real project and coding work. We suggest you get used to this way of executing code right away.

What you just created is an R script, as compared to a function, which would have the word function at the start. More on that later. You can save the R script to a file with a .R extension, for instance test-script.R.

Once you’ve done that, go to the little triangle symbol in the upper left corner of the editor and pick ‘Source R File’. You should see stuff happening on the right sidebar of Positron. Some variables should show up and a plot appear in the Plots pane. Congratulations, you just ran your first R script inside Positron! In the Session pane (the R console), you can also see the command that was executed to run the script: source("path/to/your/script.R"). As a general rule, anything you can do by pressing buttons inside Positron is also possible by typing commands into the R session console or the terminal.

As mentioned, you can also run code line by line. To do so, place your cursor into the line of code you want to run, and press Ctrl/Cmd + Enter. You should see the code execute in the R console on the right side. Try that with each of the three lines of code in your script. Note that you usually need to execute code in order. Try that. Go to the R console and hit that circle icon that says “Restart R”. This clears out the previously created x and y objects. Now go into the second line of your code y <- x^2 and try to run it with Ctrl/Cmd + Enter. You should see an error message in the R console, because x does not exist yet. Go back to the first line and run it, then go back to the second line and run it again. This time it should work.

Interactive execution of code is useful during exploration and development, but for any real project work, you should always run full scripts. That way, you ensure that everything is executed in the right order and that all dependencies are met. This also makes your project reproducible. You should get used to the approach of running your code with the source() command.

Debugging R Code in Positron

As you just saw, if something went wrong running the script, you would see an error message in that console. Positron is trying to help you avoid bugs. Let’s look at a few features. Replace one of the round parentheses ( with a square bracket [. As you do so, you should see the Problems tab go from No problems detected to a statement about what is wrong. Sometimes these statements are more informative, sometimes less. But it does tell you where in your code something looks off, so you can inspect and fix. You will also notice that the syntax highlighting of the code changed to show where the mistake is.

Let’s for now ignore the warning. Save the file again and try to run it. You can run it again as before by clicking the triangle button. Or you can go into the R console, use the arrow up button to pull up the last command, which should be the source... statement, and hit enter to re-execute. You should see an error message appear in the console. You will also see a Show Traceback option. Click on it, and something maybe not too informative will show. What traceback means is it tries to figure out where exactly the error happened. For a simple script like the one we are running, this doesn’t provide more information than the error message itself. But once you start writing more complex code, it is quite often the case that your script calls some function which calls another function,… And then it’s often tricky to figure out where the error occurred and how it got triggered. The Traceback information is often helpful.

If you haven’t done yet, fix the error and run again to make sure things are working again.

Code formatting

Positron gives you syntax highlighting, which is very useful for reading and writing code. For instance it makes it much easier to ensure that for every open ( or { you have a matching ) or }. Another nice feature of Positron is that it comes pre-configured with the air formatter which automatically formats code in a way that makes it easier to read. In general, whenever you save your file, it will reformat whatever you wrote to make it follow a certain structure. If you are an advanced coder and/or have your own style, maybe you don’t want this extra help. But it’s very useful for novice coders, it really makes code easier to read.

More features

There are a lot more features built into Positron that make working with R easier. If you are an RStudio user, you might likely find most - but not all - of the features you are used to. Positron is still fairly new, so not all features are there yet.

Summary

We discussed how to use R from within Positron. We will pretty much always use R that way.

Further Resources

Test yourself

What is the recommended way to execute R code for a real project in Positron?

For reproducible work you should save your script and execute the entire file with Source R File (or source("path/to/script.R")), not just scattered lines.

  • False
  • False
  • True
  • False

When a mismatched bracket triggers a message in the Problems tab and changes the syntax highlighting, what should you do?

Use the feedback from the Problems tab and the highlighting to find the mismatch, correct the syntax, and then re-run the script.

  • False
  • True
  • False
  • False

After restarting R, you run y <- x^2 before defining x and get an error. What does this tell you about running code?

Objects have to exist before you use them. After a restart you must recreate x (or run the script from the top) before executing y <- x^2.

  • False
  • False
  • False
  • True

Practice

  • If you previously went through the Brief Introduction to Positron course before you had R installed, revisit it and complete the exercises there that involved R code.
  • Create a short script in Positron, save it, and run it with Source R File, then re-run it from the console with source("your-script.R") to compare.
  • Intentionally introduce an error in your script, watch how the Problems tab and syntax highlighting change, then fix it.