RStudio & Running Code

Reviewed & published by Brayan K

RStudio is the standard workspace for R — a single window that combines a script editor, a live console, and panes for your variables, plots, and help, so you can write and run R comfortably.

Part of the free R course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

By the end of this lesson you'll know how R and RStudio relate, the difference between the console and a script, how to run code line by line or all at once, and how the working directory affects file paths.

What You'll Learn in This Lesson

1️⃣ Scripts: Code You Keep

A script is a plain text file (ending in .R) full of R commands. Unlike typing into the console, a script is a permanent record you can re-run, edit, and share. Inside RStudio you write in the top-left editor pane and send lines to the console to run them.

Notice cat() prints values without quotes and lets you mix text and numbers, while "\n" adds a line break. message() is handy for status updates that aren't part of your results.

2️⃣ The Console: Instant Feedback

The console runs code the moment you press Enter — perfect for quick checks. Two functions are invaluable for exploring: ls() lists the objects you've created, and str() ("structure") shows the shape of any object at a glance.

# In RStudio the Console (bottom-left) runs code instantly.
# Try these interactive commands to inspect your environment.

x <- 10
y <- 25

# ls() lists the variables (objects) you've created this session:
ls()                 # -> [1] "x" "y"

# Re-running a name prints its current value:
x + y                # -> [1] 35

# str() gives a compact summary of any object's structure:
str(c(1, 2, 3))      # -> num [1:3] 1 2 3

str() told us we have a numeric vector of 3 values: num [1:3] 1 2 3. You'll reach for str() constantly once you start loading real data.

3️⃣ The Working Directory

When you read or write files, R uses the working directory as its starting point. getwd() shows it; setwd("path") changes it. Getting this right prevents the most common beginner frustration: "R can't find my file."

# A typical RStudio workflow combines a script with the console.
# Working directory: where R reads and writes files by default.

# getwd()            # prints your current working directory, e.g. "/home/you/projects"

# Comments explain WHY. Use them generously in scripts.
prices <- c(9.99, 19.99, 4.50)
n_items <- length(prices)            # how many elements?

cat("You have", n_items, "items.\n") # -> You have 3 items.
cat("Most expensive:", max(prices), "\n")

Your turn. Fill in the ___ blank and run it, comparing with the expected output.

# 🎯 YOUR TURN — replace each ___ then run it.

# 1) Make a vector of three temperatures
temps <- ___   # 👉 replace ___ with c(18, 21, 16) (or three readings of your own)

# 2) Print how many readings there are with length()
cat("Readings:", length(temps), "\n")

# 3) Print the average with mean(), rounded to 1 decimal
cat("Average:", round(mean(temps), 1), "\n")

# ✅ Expected output (for c(18, 21, 16)):
# Readings: 3
# Average: 18.3

Mini-Challenge: A Session Summary

Write this one from scratch using the outline, then run it and check it against the example output.

Common Errors (and the fix)

Pro Tips

📋 Quick Reference — Running Code

TaskR Syntax
Print mixed text/numberscat("n =", n, "\n")
Status messagemessage("done")
List your objectsls()
Inspect structurestr(x)
Show working directorygetwd()
Run a saved scriptsource("a.R")

🎉 Lesson Complete!

Practice quiz

What is the relationship between R and RStudio?

  • RStudio is the language; R is the editor
  • R is the language/engine; RStudio is an IDE around it
  • They are the same program
  • R replaced RStudio

Answer: R is the language/engine; RStudio is an IDE around it. R is the language and engine; RStudio is an IDE that sits on top of it.

What file extension does an R script use?

  • .R
  • .py
  • .txt
  • .rmd

Answer: .R. R scripts are plain text files ending in .R.

Which function lists the objects you have created this session?

  • str()
  • getwd()
  • ls()
  • list()

Answer: ls(). ls() lists the names of objects in your environment.

What does getwd() return?

  • The R version
  • A list of files
  • Your variables
  • The current working directory path

Answer: The current working directory path. getwd() shows the folder R uses as its working directory.

Which function gives a compact summary of an object's structure?

  • str()
  • ls()
  • cat()
  • message()

Answer: str(). str() reports the structure and type of any object.

What does cat() do compared to printing?

  • Saves to a file
  • Prints values without quotes, mixing text and numbers
  • Only prints numbers
  • Returns a value silently

Answer: Prints values without quotes, mixing text and numbers. cat() concatenates and prints without quotation marks.

What does " " produce inside cat()?

  • A tab
  • A backslash
  • A newline (line break)
  • A space

Answer: A newline (line break). is the newline escape, so output starts on a new line.

How do you run an entire saved script from the console?

  • run("a.R")
  • import("a.R")
  • exec("a.R")
  • source("a.R")

Answer: source("a.R"). source("a.R") executes every line of the saved file in order.

What is the keyboard shortcut to run the current line in RStudio?

  • Ctrl/Cmd + Enter
  • Ctrl + S
  • Alt + R
  • Shift + Space

Answer: Ctrl/Cmd + Enter. Ctrl/Cmd + Enter sends the current line to the console and advances.

Why does an RStudio Project (.Rproj) help with file paths?

  • It compiles your code
  • It hides the console
  • It sets the working directory automatically
  • It installs packages

Answer: It sets the working directory automatically. A Project sets the working directory for you, avoiding path headaches.

Continue this course

Frequently asked questions

What is the difference between R and RStudio?

R is the actual programming language and engine that runs your code. RStudio is an IDE (integrated development environment) — a polished application that gives you a script editor, a console, a pane showing your variables, a plots viewer, and help — all in one window. You install R first, then RStudio sits on top of it. You can use R without RStudio, but RStudio makes writing and running R far more comfortable, especially for beginners.

Should I type code in the console or in a script?

Use the console for quick, throwaway experiments — checking a value or testing one line. Use a script (a .R file) for any work you want to keep, repeat, or share, because a script is a permanent record you can re-run from top to bottom. The common workflow is to write code in the script editor and send lines to the console with Ctrl+Enter (Cmd+Enter on Mac) to run them as you go.

What is a working directory and why does it matter?

The working directory is the folder R treats as 'here' — it's where R looks when you read a file like read.csv("data.csv") and where it writes files by default. Check it with getwd() and set it with setwd("path"). If R says it can't find your file, the working directory is usually the culprit. In RStudio, using Projects (a .Rproj file) sets the working directory for you automatically, which avoids most path headaches.

How do I run an entire script at once?

In RStudio, click the Source button or press Ctrl+Shift+Enter to run the whole active script. From the console you can run a saved file with source("analysis.R"). To run just a few lines, select them and press Ctrl+Enter. Running a script executes its commands in order, exactly as if you'd typed each line into the console yourself.