01 / 21
R

Running
R Code

Learn to execute R commands in the console for instant feedback and write reusable R scripts (.R files) for reproducible analysis.

R Programming

What is R?

R is a free, open-source programming language designed for statistics and data analysis. When you "run R code," you send instructions to the R interpreter, which reads, evaluates, and returns results.

Interpreted
R reads your code line by line: no compiling step needed before running.
Interactive
Type a command, press Enter, see the result immediately in the console.
Scriptable
Save commands in a .R file to rerun entire analyses with one click.

The RStudio Environment

RStudio is an Integrated Development Environment (IDE) that makes working with R easier. It organizes your workspace into four main panes.

Source Editor Write .R scripts here mean(c(1, 2, 3)) print("Hello R") Environment Variables and data x : num 42 data : 150 obs. of 5 Console Run code interactively > 2 + 2 [1] 4 Plots / Help / Files Visualizations and docs

Two Ways to Run R Code

R gives you two primary ways to execute code. Understanding both is essential for any R programmer.

Console (Interactive)
Type commands directly at the > prompt. Great for quick calculations, testing ideas, and exploring data.
R Script (.R File)
Write multiple lines in a file, then run them all at once. Essential for reproducible, shareable analysis.

The R Console

The console is the interactive command line where R waits for your input. The > prompt means R is ready.

> 2 + 2
[1] 4

> sqrt(144)
[1] 12

> x <- 10
> x * 3
[1] 30

The + Continuation Prompt

If you press Enter before a command is complete (e.g., missing a closing parenthesis), R shows a + prompt, asking for more input.

> mean(c(1, 2, 3)
+ )
[1] 2

R Scripts (.R Files)

An R script is a plain text file with a .R extension containing a sequence of R commands. You write the script in the Source Editor and run it when ready.

# my_analysis.R
# Calculate average test scores

scores <- c(85, 92, 78, 96, 88)
avg <- mean(scores)
print(paste("Average:", avg))

Running Scripts: Three Methods

1
Run Selected Line(s): Place your cursor on a line (or highlight multiple lines) and press Ctrl+Enter (Cmd+Return on Mac). Only the selected code runs.
2
Source Entire Script: Press Ctrl+Shift+S (or click the Source button). This runs every line in the file from top to bottom.
3
source() Function: Type source("my_analysis.R") in the console to run a script by name from the command line.

Console vs Script

Console R Script (.R)
Saved? No: lost when you close R Yes: saved as a .R file
Execution One command at a time One line, selection, or entire file
Best for Quick tests, exploration Reproducible analysis
Editable? Limited (history recall) Full text editing
Comments Rarely used Essential: document your work

Step-by-Step Workflow

1
Open RStudio and create a new R script: File → New File → R Script.
2
Write your code in the Source Editor. Add comments with # to explain each section.
3
Save the script with a descriptive name (e.g., analysis.R). Use Ctrl+S.
4
Run line by line with Ctrl+Enter to test as you go. Fix errors immediately.
5
Source the entire script with Ctrl+Shift+S when everything works. Check the console for output.

Example 1: Console Session

You want to quickly compute the mean and standard deviation of five quiz scores.

> scores <- c(72, 85, 90, 68, 95)
> mean(scores)
[1] 82
> sd(scores)
[1] 11.60172
> max(scores) - min(scores)
[1] 27

Example 2: R Script

Now write the same analysis as a reusable R script with comments.

my_stats.R
# my_stats.R
# Compute descriptive statistics for quiz scores

scores <- c(72, 85, 90, 68, 95)

# Calculate stats
avg <- mean(scores)
stdev <- sd(scores)
range_val <- max(scores) - min(scores)

# Display results
cat("Mean:", avg, "\n")
cat("SD:", stdev, "\n")
cat("Range:", range_val, "\n")

Example 3: Reading Errors

When R encounters a problem, it prints an error message. Learning to read these is a critical skill.

> mean(scores
+
+ # Oops! Missing closing parenthesis
+ # Press Esc to cancel

> meen(scores)
Error in meen(scores) :
  could not find function "meen"

> mean(scores) # Fixed: correct spelling
[1] 82

The source() Function

The source() function lets you run an entire R script from the console or from inside another script. It is the programmatic way to execute .R files.

# Run a script by providing its file path
> source("my_stats.R")
Mean: 82
SD: 11.60172
Range: 27

# Run a script in a subfolder
> source("scripts/clean_data.R")

Common Mistakes

✕ Forgetting Parentheses
Writing mean scores instead of mean(scores). R functions always need parentheses, even with no arguments: ls().
✕ Not Saving the Script
Typing code only in the console means your work vanishes when you close R. Always save important code in a .R file.
✕ Wrong Working Directory
Using source("file.R") when R is looking in the wrong folder. Check with getwd() and fix with setwd().

Summary of Key Concepts

Concept What It Does Key Shortcut
Console Interactive, line-by-line execution Type + Enter
R Script (.R) Saved, reusable code file Ctrl+Shift+N (new)
Run Line Execute current/selected line Ctrl+Enter
Source Script Run entire .R file top to bottom Ctrl+Shift+S
source() Run a .R file programmatically source("file.R")
Comments (#) Annotate code; ignored by R Ctrl+Shift+C (toggle)

Question 1 of 5

What does the > symbol in the R console indicate?

Question 2 of 5

Which keyboard shortcut runs the current line of an R script in RStudio?

Question 3 of 5

What is the main advantage of saving code in an R script (.R file) rather than typing it only in the console?

Question 4 of 5

You see a + prompt instead of > in the console. What should you do first?

Question 5 of 5

Which of the following correctly uses the source() function to run an R script?