Types, memory, debugging, reproducibility. Light R.
Q1 · Programs, data, and R
A program is instructions that transform input data into output (tables, plots, model fits).
input_rows <-nrow(reef) # how many rows enter the pipelineoutput_sites <-length(unique(reef$site)) # how many sites after summarisingc(input_rows = input_rows, output_sites = output_sites) # named result vector
input_rows output_sites
60 3
Q2 · Assignment and names
<- stores a value under a name (object).
mean_depth <-mean(reef$depth_m) # store summary under a clear namemean_depth # retrieve by name
[1] 7.591667
rm(mean_depth) # remove binding (free name)
Q3 · Types and coercion
Every value has a type (numeric, character, logical, …).
typeof(reef$count) # should be double/integer
[1] "integer"
char_counts <-as.character(reef$count[1:3]) # simulate import as textas.numeric(char_counts) # explicit conversion back
[1] 4 12 1
Q4 · Memory: copy vs modify
R often shares memory until you modify a copy (copy-on-write).
a <- reef$count # share column vectorb <- a # b points at same data until changedb[1] <-999L # replace triggers copy for ba[1] # original column unchanged in reef
[1] 4
Q5 · Files and paths
Scripts live in directories; data live in files with paths.
# A tibble: 3 × 2
site total
<chr> <int>
1 East 219
2 North 176
3 South 196
Q18 · Reading error messages
Errors read bottom-up: what failed, then the call stack.
# Example: intentional typo (run to see error in console when knitting locally)# mean(reef$counts) # counts vs counttryCatch(mean(reef$counts), error =function(e) conditionMessage(e))
[1] NA
Q19 · Documentation & help()
?mean, help(mean), and package vignettes are authoritative.
args(mean) # formal arguments
function (x, ...)
NULL
# help(mean) # run in RStudio for full help page
Q20 · CS capstone plan
Before writing code for a new dataset, sketch on paper:
plan <-list(input ="acoustic_detections.csv",output ="detections per animal_id",checks =c("no negative detections", "animal_id not empty"),steps =c("read.csv", "group_by + summarise", "ggplot if needed"))plan
$input
[1] "acoustic_detections.csv"
$output
[1] "detections per animal_id"
$checks
[1] "no negative detections" "animal_id not empty"
$steps
[1] "read.csv" "group_by + summarise" "ggplot if needed"