Welcome!

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


Part 1: Install R and RStudio (30 minutes)

Step 1: Install R

R is the programming language we’ll use. Download it from:

https://cloud.r-project.org/

Figure 1. Download R according to your operating system.

  1. Click on your operating system (Windows, Mac, or Linux)
  2. For Windows: Click “base”, then “Download R-4.x.x for Windows”
  3. For Mac: Click the .pkg file appropriate for your Mac
  4. Run the installer with default settings

Step 2: Install RStudio

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.

  1. Scroll down to list of operating systems and choose yours
  2. Click Download
  3. Run the installer with default settings

Step 3: Verify Installation

  1. Open RStudio (not R!)

Figure 3. Open RStudio (left), not R (right).

  1. You should see a window divided into panels (we’ll explain these in Part 2!)

  2. In the Console (bottom left), type: 2 + 2 and press Enter

  3. If you see [1] 4, congratulations - R is working!

# Try this in your console:
2 + 2

Part 2: Understanding the RStudio Interface (20 minutes)

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.

The Big Picture

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.

The Two Most Important Panels

For beginners, you only need to focus on 2 panels at first:

  1. Script (top left) - where you WRITE code
  2. Console (bottom left) - where you SEE results

Think of it Like Cooking

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!

🔵 Panel 1: Script / Source Editor (Top Left)

Figure 6. The Script panel is where you write and save your code.

What is it?

This is where you write and save your code. Think of it like a Word document, but for R code.

Key Points

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)

How to Use It

Opening a new script:

  1. Go to File → New File → R Script
  2. Or use keyboard shortcut: Ctrl + Shift + N (Windows) / Cmd + Shift + N (Mac)

Figure 7. Creating a new R script from the File menu.

Saving your script:

  1. Go to File → Save
  2. Or use keyboard shortcut: Ctrl + S (Windows) / Cmd + S (Mac)
  3. Give it a name ending in .R (example: beetle_analysis.R)

Figure 8. Never forget to save your script.

Running your code:

  1. Put your cursor on the line you want to run
  2. Press Ctrl + Enter (Windows) / Cmd + Enter (Mac)
  3. The result appears in the Console below

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!

🔴 Panel 2: Console (Bottom Left)

Figure 10. The Console panel shows output from your code.

What is it?

This is where R “talks back” to you. When you run code, the results appear here.

Key Points

Feature Description
Purpose Shows output, results, and messages from R
Analogy Like a calculator display
Saved? ❌ NO - everything disappears when you close RStudio

Understanding the Console Symbols

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.

Example: What You’ll See

When you run this code in your Script:

2 + 2

You’ll see this in the Console:

> 2 + 2
[1] 4

The [1] just means “this is the first element of the result.” For now, you can ignore it!

🟢 Panel 3: Environment (Top Right)

Figure 11. The Environment panel shows objects R is remembering.

What is it?

This panel shows all the “things” R is currently remembering - your data, variables, and other objects.

Key Points

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!

Example

When you run this code:

x <- 5
my_name <- "Beetle Researcher"

The Environment panel will show:

Environment (Global)
─────────────────────
x              5
my_name        "Beetle Researcher"

Tip: If you click on a data object, RStudio will open it in a spreadsheet view!

🟡 Panel 4: Files / Plots / Packages / Help (Bottom Right)

Figure 12. The bottom right panel has multiple tabs.

What is it?

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

Your First Interaction with RStudio

Let’s practice! Follow these steps exactly:

Step 1: Open RStudio

Find RStudio on your computer and open it. (Open RStudio, not R!)

Step 2: Create a New Script

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.

Step 3: Type Your First Code

In the Script panel (top left), type:

# My first R code
# The hashtag (#) means this line is a comment - R ignores it

# Let's do some math
2 + 2

# Let's create an object
my_number <- 10

# Let's see what's in my_number
my_number

Step 4: Run Your Code

  1. Put your cursor on the line 2 + 2
  2. Press Ctrl + Enter (Windows) or Cmd + Enter (Mac)
  3. Look at the Console (bottom left) - you should see [1] 4

Now run the other lines one by one. Watch what happens in the Console and Environment!

Step 5: Check the Environment

After running my_number <- 10, look at the Environment panel (top right).

You should see:

my_number    10

🎉 Congratulations! You’ve successfully:

  • Written code in a Script
  • Run code using Ctrl+Enter (or Cmd+Enter)
  • Seen results in the Console
  • Created an object that appears in the Environment

Step 6: Save Your Script

  1. Press Ctrl + S (Windows) or Cmd + S (Mac)
  2. Create a new folder called R_Workshop in your Documents
  3. Name the file practice.R
  4. Click Save

The Flow of Code: How Everything Connects

Here’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)    │
└───────────────────┘

Quick Reference: Where to Look

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)

Part 3: Common Questions and Problems

“I only see 3 panels, not 4!”

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.

“My panels are in different positions!”

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.

“I typed code in the Console and now I can’t find it!”

Solution: Code typed directly in the Console is not saved. Always write important code in a Script!

  • Script = Saved (like a document) ✅
  • Console = Not saved (like a calculator) ❌

“I see a + instead of > in the Console!”

Solution: R thinks you haven’t finished your command. This usually means:

  • You forgot to close a parenthesis )
  • You forgot to close a quote "
  • You forgot to finish a command

Fix: Press Escape to cancel, then check your code and try again.

“Nothing happens when I press Enter!”

Solution: Make sure you’re pressing Ctrl + Enter (Windows) or Cmd + Enter (Mac), not just Enter.

  • Enter alone = New line in the Script (doesn’t run code)
  • Ctrl/Cmd + Enter = Run the current line

“I see red text in the Console!”

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

“My Environment is empty but I ran my code!”

Solution: Check these things:

  1. Did you actually run the code? (Press Ctrl+Enter)
  2. Did you save to an object? x <- 5 saves, but 5 alone doesn’t
  3. Did you get an error? Check the Console for red text

Part 4: R Projects - Essential for Organization (15 minutes)

Why Projects Matter

This is the #1 mistake beginners make: Working without a project, with files scattered everywhere.

Without a project:

  • Files are scattered across your computer
  • You can’t find your files months later
  • Your code breaks on other computers

With a project:

  • Everything is in ONE folder
  • Easy to find and organize
  • Your code works anywhere!

Creating the Workshop Project

Step 1: Create New Project

  1. In RStudio, go to File → New Project…

Figure 13. Creating a new R Project.

  1. Choose “New Directory”

Figure 14. Creating New Directory.

  1. Choose “New Project”

Figure 15. Choose “New Project”.

  1. Fill in:
    • Directory name: Insect_Ecology_Workshop
    • Create as subdirectory of: Choose your Documents folder
  2. Click “Create Project”

Figure 16. Create Directory name, subdirectory and Create Project.

Step 2: Create Folder Structure

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

Step 3: Verify It Worked

Run this in the Console:

# List files and folders
list.files()

You should see: data, figures, output, scripts

The Golden Rules of Projects

Rule 1: Always Open Your Project First

Before doing ANY work:

  1. Find the .Rproj file in your project folder
  2. Double-click it to open RStudio with your project loaded

Or in RStudio: File → Open Project

Figure 17. Open R Project file.

Rule 2: Never Use setwd()

# ❌ BAD - Never do this!
setwd("C:/Users/John/Desktop/thesis/chapter2/analysis/data")
data <- read.csv("beetles.csv")
# ✅ GOOD - Use relative paths from your project folder
data <- read.csv("data/raw/beetles.csv")

Rule 3: Keep Raw Data Sacred

Never modify files in data/raw/. If you need to clean data:

  1. Read from data/raw/
  2. Clean in R
  3. Save to data/processed/

Figure 18. Data folder structure consist of raw folder (for all raw data) and processed folder (for all processed data).


Part 5: Install Required Packages (15 minutes)

Packages add extra functionality to R. We need several for this workshop.

What are Packages?

Think of R like a smartphone:

  • Base R = The phone’s built-in apps (calculator, calendar, contacts)
  • Packages = Apps you download (Spotify, Instagram, games)
  • install.packages() = Download the app (only once)
  • library() = Open the app (every time you use it)

Install Workshop Packages

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.

Verify Packages Installed Correctly

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 package

If all packages load without errors, you’re ready!


Part 6: R Basics Self-Study (20 minutes)

Complete these exercises to familiarize yourself with R syntax.

Exercise 1: Objects and Assignment

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_protected

Keyboard shortcut: Press Alt + - (Windows) or Option + - (Mac) to type <-

Your turn: Create objects for:

  • n_traps = 20
  • habitat_type = “grassland”
  • is_summer = TRUE

Exercise 2: Vectors

Vectors 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 30

Your turn:

  1. Create a vector called beetle_counts with values: 5, 12, 8, 3, 15, 22, 9
  2. Calculate the mean
  3. Find how many values are greater than 10

Exercise 3: Data Frames

Data 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:

  1. Access only the grassland rows
  2. Calculate the mean beetles for all sites

Exercise 4: Getting Help

# Get help for a function
?mean

# Search for topics
??diversity

# See examples
example(mean)

Part 7: Keyboard Shortcuts Reference

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

Checklist Before Workshop

Please confirm you have completed everything:

Software Installation

Understanding RStudio

Packages

Project Setup

R Basics


Troubleshooting

Package Installation Fails

Try these solutions:

# Solution 1: Install with dependencies
install.packages("packagename", dependencies = TRUE)

# Solution 2: Try a different mirror
chooseCRANmirror()  # Select a different location

# Solution 3: Update R (if very old version)
# Download latest R from https://cloud.r-project.org/

Can’t Find My Project

  • Look for the .Rproj file in the folder you created
  • Check your Documents folder
  • In RStudio: File → Recent Projects

General Tips

  • Read error messages carefully - they often tell you what’s wrong
  • Google the error message (someone else had this problem!)
  • Check for typos (R is case-sensitive: Meanmean)

See You at the Workshop!

If you completed everything above, you’re ready! 🎉

During the workshop, we’ll:

  • Day 1: Import data, wrangle it, explore patterns, choose focal taxa
  • Day 2: Visualize, calculate diversity, ordination (NMDS), statistical tests

Bring:

  • Your laptop with R and RStudio installed
  • The workshop project set up and ready
  • Questions!

If you have problems with installation, please contact the instructor BEFORE the workshop day.