This document will help you prepare for our 2-day R workshop. Please complete all sections before arriving - this will ensure we can dive straight into the exciting parts during the workshop!
Time needed: Approximately 1-2 hours
R is the programming language we’ll use. Download it from:
Figure 1. Download R according to your operating system.
RStudio is the interface that makes R easier to use. Download it from:
https://posit.co/download/rstudio-desktop/
Figure 2. Download RStudio according to your operating system.
|
|
|
|
Figure 3. Open RStudio (left), not R (right). |
|
You should see a window divided into panels (we’ll explain these in Part 2!)
In the Console (bottom left), type: 2 + 2 and press
Enter
If you see [1] 4, congratulations - R is
working!
When you first open RStudio, you might feel overwhelmed by all the panels and buttons. Don’t panic! This section will guide you through everything you need to know.
RStudio is divided into 4 main panels (sometimes called “panes”). Each panel has a specific job.
Figure 4. The RStudio interface with four main panels.
Here’s the layout:
┌─────────────────────────────────────┬─────────────────────────────────────┐
│ │ │
│ 🔵 SOURCE / SCRIPT │ 🟢 ENVIRONMENT │
│ "Where you WRITE code" │ "What R remembers" │
│ (Top Left) │ (Top Right) │
│ │ │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ │ │
│ 🔴 CONSOLE │ 🟡 FILES / PLOTS / HELP │
│ "Where R TALKS back" │ "Supporting tools" │
│ (Bottom Left) │ (Bottom Right) │
│ │ │
└─────────────────────────────────────┴─────────────────────────────────────┘
Note: When you first open RStudio, you might only see 3 panels like in the Figure 5. The Script panel (top left) only appears when you open or create a script file. We’ll do that soon!
Figure 5. Overview when you first open RStudio.
For beginners, you only need to focus on 2 panels at first:
| Panel | Cooking Analogy | What It Does |
|---|---|---|
| Script | Your recipe book | You write down all your steps. You can save it, edit it, and use it again tomorrow. |
| Console | Your kitchen | This is where the actual cooking happens. R reads your recipe and does the work here. |
🔑 Golden Rule: Always write your code in a Script, not directly in the Console. The Console doesn’t save your work - when you close RStudio, everything in the Console disappears!
Figure 6. The Script panel is where you write and save your code.
This is where you write and save your code. Think of it like a Word document, but for R code.
| Feature | Description |
|---|---|
| Purpose | Write, edit, and save your R code |
| Analogy | Like a Word document for code |
| Saved? | ✅ YES - your work is saved in a file |
| File type | .R files (example: my_analysis.R) |
Opening a new script:
Ctrl + Shift + N (Windows) /
Cmd + Shift + N (Mac)Figure 7. Creating a new R script from the File menu.
Saving your script:
Ctrl + S (Windows) /
Cmd + S (Mac).R (example:
beetle_analysis.R)Figure 8. Never forget to save your script.
Running your code:
Ctrl + Enter (Windows) / Cmd + Enter
(Mac)Figure 9. Place cursor on a line and press Ctrl+Enter (or Cmd+Enter) to run it.
Tip: You can also select multiple lines and run them all at once!
Figure 10. The Console panel shows output from your code.
This is where R “talks back” to you. When you run code, the results appear here.
| Feature | Description |
|---|---|
| Purpose | Shows output, results, and messages from R |
| Analogy | Like a calculator display |
| Saved? | ❌ NO - everything disappears when you close RStudio |
| Symbol | Meaning | What to Do |
|---|---|---|
> |
R is ready | R is waiting for your command. You can type or run code. |
+ |
R is waiting | R thinks you haven’t finished typing. Press Escape to cancel. |
| Red text | Error message | Something went wrong. Read the message for clues! |
| Blue text | Message/warning | Information from R, not necessarily a problem. |
Figure 11. The Environment panel shows objects R is remembering.
This panel shows all the “things” R is currently remembering - your data, variables, and other objects.
| Feature | Description |
|---|---|
| Purpose | Shows what objects exist in R’s memory |
| Analogy | Like your desk - shows what you’re currently working with |
| Important | If your data isn’t here, R doesn’t know about it! |
Figure 12. The bottom right panel has multiple tabs.
This panel has multiple tabs for different helper tools:
| Tab | Purpose | You’ll Use It For |
|---|---|---|
| Files | Browse folders on your computer | Finding your data files |
| Plots | Display graphs and charts | Viewing your visualizations |
| Packages | Manage R packages | Installing new packages |
| Help | Read documentation | Learning about functions |
Let’s practice! Follow these steps exactly:
Find RStudio on your computer and open it. (Open RStudio, not R!)
Go to File → New File → R Script
You should now see 4 panels. The top left panel (Script) should be empty and ready for typing.
In the Script panel (top left), type:
2 + 2Ctrl + Enter (Windows) or
Cmd + Enter (Mac)[1] 4Now run the other lines one by one. Watch what happens in the Console and Environment!
After running my_number <- 10, look at the
Environment panel (top right).
You should see:
my_number 10
🎉 Congratulations! You’ve successfully:
Ctrl + S (Windows) or Cmd + S
(Mac)R_Workshop in your
Documentspractice.RHere’s how the panels work together:
┌─────────────────────────────────┐
│ 1. YOU write code in SCRIPT │
│ (top left panel) │
└───────────────┬─────────────────┘
│
│ Press Ctrl+Enter (or Cmd+Enter)
▼
┌─────────────────────────────────┐
│ 2. R reads and executes │
│ your code │
└───────────────┬─────────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌───────────────┐ ┌───────────────────┐
│ 3a. Results │ │ 3b. New objects │
│ appear in │ │ appear in │
│ CONSOLE │ │ ENVIRONMENT │
│ (bottom left) │ │ (top right) │
└───────────────┘ └───────────────────┘
│
▼ (if you made a plot)
┌───────────────────┐
│ 3c. Plots appear │
│ in PLOTS tab │
│ (bottom right) │
└───────────────────┘
| I want to… | Look at this panel |
|---|---|
| Write code | Script (top left) |
| See output/results | Console (bottom left) |
| See my data and objects | Environment (top right) |
| See my plots/graphs | Plots tab (bottom right) |
| Browse files | Files tab (bottom right) |
| Get help | Help tab (bottom right) |
Solution: The Script panel only appears when you have a script open.
Go to File → New File → R Script and the fourth panel will appear.
Solution: That’s okay! You can rearrange panels, but the default layout is fine.
If you want to reset: Go to View → Panes → Pane Layout and choose your preferred arrangement.
Solution: Code typed directly in the Console is not saved. Always write important code in a Script!
+ instead of > in the
Console!”Solution: R thinks you haven’t finished your command. This usually means:
)"Fix: Press Escape to cancel, then check your code and try again.
Solution: Make sure you’re pressing
Ctrl + Enter (Windows) or Cmd + Enter (Mac),
not just Enter.
Solution: Red text usually means an error. Don’t panic! Read the message - it often tells you what’s wrong.
Common errors:
| Error Message | Likely Cause | Fix |
|---|---|---|
object 'x' not found |
Typo in object name, or you forgot to create it | Check spelling, run the line that creates the object |
could not find function |
Typo in function name, or package not loaded | Check spelling, run library(package_name) |
unexpected symbol |
Missing comma, parenthesis, or quote | Check your syntax carefully |
Solution: Check these things:
x <- 5 saves, but
5 alone doesn’tThis is the #1 mistake beginners make: Working without a project, with files scattered everywhere.
Without a project:
With a project:
Figure 13. Creating a new R Project.
Figure 14. Creating New Directory.
Figure 15. Choose “New Project”.
Insect_Ecology_WorkshopFigure 16. Create Directory name, subdirectory and Create Project.
In the Console, run this code to create organized folders:
# Create folder structure for the workshop
dir.create("data")
dir.create("data/raw")
dir.create("data/processed")
dir.create("scripts")
dir.create("output")
dir.create("figures")Your project should now look like this:
Insect_Ecology_Workshop/
│
├── Insect_Ecology_Workshop.Rproj ← Double-click this to open your project!
│
├── data/
│ ├── raw/ ← Put original data here (NEVER modify!)
│ └── processed/ ← Cleaned data goes here
│
├── scripts/ ← Your R scripts
│
├── output/ ← Results, tables
│
└── figures/ ← Saved plots
Before doing ANY work:
.Rproj file in your project folderOr in RStudio: File → Open Project
Figure 17. Open R Project file.
setwd()Never modify files in data/raw/. If you need to clean
data:
data/raw/data/processed/Figure 18. Data folder structure consist of raw folder (for all raw data) and processed folder (for all processed data).
Packages add extra functionality to R. We need several for this workshop.
Think of R like a smartphone:
Copy and paste this entire block into your Console and press Enter:
# Install all required packages for the workshop
# This may take 5-10 minutes - be patient!
install.packages(c(
"tidyverse", # Data wrangling and visualization
"vegan", # Community ecology analyses
"ape", # PCoA and phylogenetics
"indicspecies", # Indicator species analysis
"ggplot2", # Visualisasi data
"patchwork" # Combining plots
))You’ll see lots of text scrolling by - this is normal! Wait until you
see the > prompt again.
Run this code to check:
# Try loading each package - you should see NO errors
library(tidyverse)
library(vegan)
library(ape)
library(indicspecies)
library(ggplot2)
library(patchwork)
# If you see "Error in library(xxx) : there is no package called 'xxx'"
# Run: install.packages("xxx") for that packageIf all packages load without errors, you’re ready!
Complete these exercises to familiarize yourself with R syntax.
In R, we store information in “objects” using
<- (the assignment arrow).
# Create objects:
species_count <- 42 # A number
site_name <- "Forest_A" # Text (needs quotes!)
is_protected <- TRUE # Logical (TRUE or FALSE)
# View objects by typing their name:
species_count
site_name
is_protectedKeyboard shortcut: Press Alt + -
(Windows) or Option + - (Mac) to type
<-
Your turn: Create objects for:
n_traps = 20habitat_type = “grassland”is_summer = TRUEVectors are collections of values. Create them with
c():
# Create a vector of abundances
abundances <- c(12, 45, 23, 8, 67, 34)
# Calculate statistics
sum(abundances) # Total: 189
mean(abundances) # Average: 31.5
max(abundances) # Maximum: 67
length(abundances) # How many: 6
# Extract elements with [ ]
abundances[1] # First element: 12
abundances[c(1,3,5)] # Elements 1, 3, and 5
abundances[abundances > 30] # Elements greater than 30Your turn:
beetle_counts with values: 5,
12, 8, 3, 15, 22, 9Data frames are like spreadsheets - they have rows and columns:
# Create a simple data frame
my_data <- data.frame(
site = c("A", "B", "C", "D"),
habitat = c("forest", "forest", "grassland", "grassland"),
beetles = c(23, 18, 45, 38)
)
# View it
my_data
# Access columns with $
my_data$beetles
my_data$habitat
# Calculate mean beetles
mean(my_data$beetles)Your turn:
Essential shortcuts to memorize:
| Action | Windows/Linux | Mac |
|---|---|---|
| Run line/selection | Ctrl + Enter |
Cmd + Enter |
Assignment <- |
Alt + - |
Option + - |
| Save script | Ctrl + S |
Cmd + S |
| New script | Ctrl + Shift + N |
Cmd + Shift + N |
| Comment/uncomment | Ctrl + Shift + C |
Cmd + Shift + C |
| Find | Ctrl + F |
Cmd + F |
| Clear console | Ctrl + L |
Cmd + L |
Please confirm you have completed everything:
Software Installation
Understanding RStudio
Packages
Project Setup
R Basics
Try these solutions:
.Rproj file in the folder you createdMean ≠
mean)If you completed everything above, you’re ready! 🎉
During the workshop, we’ll:
Bring:
If you have problems with installation, please contact the instructor BEFORE the workshop day.