Chapter 1: run your first R code and draw a graph

How do I run my first R code and draw a graph?

Use R to calculate and draw: start with 2 + 3, then find the average of 6 seedling heights, 12 cm, and draw one point for each seedling.

On this page

When you first open R, even finding where to type can take a while. I'll start there with you: calculate 2 + 3, then draw the heights of six seedlings. The graph below is what we'll make in this session.

Use the figures as a guide: a horizontal axis runs left to right; a vertical axis runs bottom to top. Read a point’s seedling number below it and its height beside it.

Six blue points: seedling IDs 1 to 6 have heights 8, 11, 9, 14, 12 and 18 cm.
Open full-size image
The result you will make: one point for each seedling ID. The horizontal axis identifies seedlings, and the vertical axis shows height in centimeters.

What are R, code and running code?

R is a language for telling a computer how to calculate and draw graphs. Written instructions are called code; running code means asking the computer to carry them out.

2 + 3 is one instruction. You enter it and R calculates 5. The values you give R are data; the answers or graphs it produces are output. Our six recorded heights will be our data.

RStudio is software that helps us use R. Console is the area for typing commands and reading text results. Plots displays graphs. An R Script is a file that stores lines of code; the editor is where you write those lines. The Run button sends the selected code to R.

Downloading saves a file to your computer; installing prepares the software for use. CRAN is R's official download site, and Posit provides RStudio. Windows, macOS and Linux are operating systems: the software that runs your computer. Choose yours below.

Where do I download R and RStudio?

Install R from CRAN first, then the free RStudio Desktop from Posit. R performs the calculations; RStudio gives us a place to write code and see its output. Install both.

The similar names can be confusing at first. Follow only the section for your computer below. If R already runs inside RStudio, skip to the check at the end.

How do I install them on Windows?

  1. Open the CRAN Windows download page, click Download R … for Windows, and save the .exe. From the CRAN home page, choose Download R for Windows → base.
  2. Open the downloaded file and follow the installer to choose a language and location. The default options are suitable for getting started.
  3. Open Posit's official RStudio download page. Under RStudio Desktop → Windows, choose the Installer (.exe), download it and run it. Use the free open-source Desktop edition; this lesson needs neither Pro nor Server.
  4. Start RStudio from the Start menu. If it cannot find R, check that the R installation finished, then close and reopen RStudio.

At this check, Posit's current Windows installer is labeled Windows 11. On Windows 10 or an older system, check official compatibility first. R and RStudio have separate system requirements.

Which downloads do I choose on macOS?

  1. Choose Apple menu → About This Mac. Note the macOS version and whether the chip is Apple M-series or the processor is Intel.
  2. On the CRAN macOS page, choose arm64.pkg for Apple Silicon or x86_64.pkg for Intel. Check the minimum macOS version beside that package. Open the downloaded .pkg and complete the R installer.
  3. On the RStudio download page, choose the Desktop macOS .dmg. At this check it is a Universal package for Apple Silicon and Intel, labeled macOS 15+.
  4. Open the disk image, drag RStudio into Applications, then open RStudio from Applications.

Check the OS requirement for each program separately. Download version numbers will change; use the current official page when choosing a file.

What should I install on Linux?

A Linux distribution is a packaged version of Linux, such as Ubuntu. Architecture describes the processor family, such as x86_64 or ARM. A terminal is the system window for typing commands. A repository is a software download source, and a package manager installs software from it. Follow the linked instructions for your exact distribution and version.

Install R for your Linux distribution first, then choose an RStudio Desktop package matching the distribution and processor architecture.

  1. Check your distribution, version and architecture in system information. Open CRAN's Linux directory and follow your distribution's instructions, such as Ubuntu, Debian or Fedora. Run installation commands in the system terminal. Ubuntu's instructions cover repository setup and r-base; Fedora uses sudo dnf install R.
  2. Find Linux under Desktop on the RStudio download page. The current .deb targets Ubuntu 22/24/26 and Debian 13; .rpm targets RHEL 9/10 and Fedora. This package requires an x86_64 processor.
  3. Open the downloaded .deb or .rpm with your distribution's software installer, or use its package manager's local-package installation procedure. Once installed, launch RStudio from the applications menu.

Linux installation commands belong in the system terminal. The R code we will write next belongs in RStudio's Console. Keeping those two windows distinct helps avoid an easy first-day mix-up.

How can I check that it worked?

In RStudio's Console, enter R.version.string and then 2 + 3, pressing Enter after each. You should see your R version and then [1] 5.

I tested the plotting code with R 4.5.3. Your installed version may differ. R's own console can run these commands too. Below, I use RStudio's script editor and Run button so you can keep your code.

Where do I type the first command?

Type 2 + 3 after the Console prompt and press Enter; the printed result is [1] 5.

2 + 3

The > in Console means R is ready for input. Type 2 + 3 after it. In [1] 5, 5 is the answer; [1] says this row starts with the first value in the result. Blocks labeled “Output” below are there for you to compare with your screen.

Now choose File → New File → R Script. Save the new file as lesson.R in a folder you can find. The script stores your commands; Console shows what happens when you run them.

How do I read the code for saving numbers, finding an average and plotting?

We will save the numbers, display them, calculate their average and draw them. Try one short piece at a time.

A vector is a sequence of values. Our six heights form a numeric vector. Each individual value is an element; all six here are stored as numbers.

A function is an operation R has ready for you, such as calculating an average. Write its name followed by round brackets, with the values it needs inside. c() combines values in order; commas separate the values.

height_cm is the name I chose for the heights: cm means centimeters, and the underscore _ joins the words. Something stored in R is an object; this object holds six heights. <- saves the right-hand result under the left-hand name. This is called assignment. Type the less-than sign and hyphen together.

Enter this line to save the six heights as height_cm. R then waits for your next instruction. We will use print() in the next step to see the saved values.

Input

height_cm <- c(8, 11, 9, 14, 12, 18)

print() displays what you put inside its brackets. Run this line to see the six heights:

Input

print(height_cm)

Output

[1]  8 11  9 14 12 18

An average, or mean, is the sum of the values divided by how many values there are. Our heights add to 72 cm; 72 divided by 6 is 12 cm. mean() does that calculation. R works out the inner mean(height_cm) first, then the outer print() displays the answer.

Input

print(mean(height_cm))

Output

[1] 12

plot() draws the graph. Its first input, 1:6, means 1, 2, 3, 4, 5, 6: seedling numbers along the horizontal axis, from left to right. Its second input, height_cm, gives heights along the vertical axis, from bottom to top. Position 1 and height 8 make the first point.

A function’s inputs and settings are called arguments. Here pch = 19 selects solid circles, and col = "#0066CC" selects blue. xlab sets the horizontal-axis title; ylab sets the vertical-axis title. The setting name goes before = and its value after it. Double quotes enclose text. The two plot lines form one command; select both when you run them.

Input

plot(1:6, height_cm, pch = 19, col = "#0066CC",
     xlab = "Seedling ID", ylab = "Height (cm)")

How do I turn six numbers into a plot?

Run the following lines in order to store the six heights, print them, calculate their mean and draw their points.

This article uses simulated example data.

The code below is the complete version of the short steps above. You can keep it in one file and run it again.

height_cm <- c(8, 11, 9, 14, 12, 18)
print(height_cm)
print(mean(height_cm))
plot(1:6, height_cm, pch = 19, col = "#0066CC",
     xlab = "Seedling ID", ylab = "Height (cm)")

Paste the code into your script. Select all its lines and click Run. The first two printed results below appear in Console, and the graph appears in Plots.

[1]  8 11  9 14 12 18
[1] 12

I use a small set of whole numbers so you can check R's answer yourself: (8 + 11 + 9 + 14 + 12 + 18) / 6 = 12 cm. In the graph, point 6 is the highest at 18 cm, while point 1 is at 8 cm.

What should I check if nothing runs?

R keeps saved objects during the current working session, meaning this run of R. Run the data-saving line again after starting a fresh session.

Start with the prompt and the first error message, then rerun the missing or corrected line before running the plot.

  • A + prompt often means R is waiting for a closing quote or parenthesis. Press Escape in the RStudio console, check the whole command and run it again.
  • object 'height_cm' not found means the assignment has not succeeded in this session. Run the line beginning height_cm <- first.
  • Height_cm and height_cm are different names. Use the same capitalization every time.
  • If a plot reports figure margins too large, enlarge the Plots pane and rerun the plotting command.

Can I change one value and predict the result?

Replacing the final height of 18 with 24 raises the mean from 12 to 13 cm and moves only point 6 upward.

Before opening the solution, change that number in your script and run all the lines again. Execute the edited line to update the object in the current session.

Exercise solution
height_cm <- c(8, 11, 9, 14, 12, 24)
print(mean(height_cm))
plot(1:6, height_cm, pch = 19, col = "#0066CC",
     xlab = "Seedling ID", ylab = "Height (cm)")

The sum is 78 and 78 / 6 = 13. Point 6 is now at 24 cm. The vertical scale may expand automatically; the other five values stay unchanged.

How can I save and repeat this lesson?

Save lesson.R; reopen it later and run it from the top to rebuild the values and graph.

The working directory is the folder where R currently looks for files and saves them. In RStudio choose Session → Set Working Directory → Choose Directory, select the folder containing lesson.R and export.R, then run source("export.R"). source() runs the code in the named file from the start. PNG is an image file made of tiny picture dots called pixels. PDF is a document format suited to printing and enlargement. CSV stores table columns separated by commas and opens in spreadsheet software. Exporting means saving results in files like these.

The exported PNG is 1200 × 800 pixels; the PDF is 7.5 × 5 inches.

If you changed the last value to 24 and saw its point move, you have edited data, run the code and checked what happened. Keep the script to look things up when a symbol slips your mind. Chapter 2 will explain how those six values are stored together, how to name them and how to select one. For today, save your first graph and the script that made it.

Where can I check the technical details?

The R manual explains objects and assignment; Posit documents how the editor runs code.

What can I learn next?

Course contents