Script-first workflow in RStudio
A reliable way to work in R is to write code in a script, run it deliberately, and keep results reproducible. In RStudio, focus on three areas: the Source pane (your script), the Console (where code runs), and the Environment (objects created in your session). The goal is to treat the script as the “source of truth” and the Console as the “execution log.”
Step-by-step: create and run a script
- Create a new script file and save it (for example,
01-foundations.R). - Type code into the script, then run lines or selections (rather than typing everything into the Console).
- Re-run the whole script from top to bottom when you change something, so you can verify it still works.
Use comments to explain intent. In R, comments start with #.
# 01-foundations.R
# Purpose: practice objects, functions, and basic data types
# A simple calculation
2 + 2Objects and assignment
An object is a named container that stores a value (or a more complex structure). You create objects using assignment. The most common assignment operator is <-. Read it as “gets.”
# Create objects
x <- 10
name <- "Amina"
flag <- TRUEGood object names are descriptive and consistent. A practical convention is snake_case for multi-word names.
# Clear naming
total_sales <- 1250
average_price <- 19.99Verifiable exercise: check what you created
Run the code below and verify that each line prints the expected value.
- Listen to the audio with the screen off.
- Earn a certificate upon completion.
- Over 5000 courses for you to explore!
Download the app
x <- 10
x
name <- "Amina"
name
flag <- TRUE
flagCalling functions with arguments
Most work in R is done by calling functions. A function call looks like function_name(argument1, argument2). Arguments can be provided by position or by name.
# Positional arguments
round(3.14159, 2)
# Named arguments (often clearer)
round(x = 3.14159, digits = 2)Some functions compute summaries, others transform data, and others help you inspect objects.
Step-by-step: use a function to compute and store results
- Create input objects.
- Call a function using those objects.
- Assign the result to a new object.
- Print the result to verify it.
values <- c(10, 12, 9, 11)
mean_value <- mean(values)
mean_valueUsing help pages effectively
R includes built-in documentation for functions. Use ? to open a help page, and help() if you prefer a function call. The help page tells you what the function does, its arguments, details, and examples.
?mean
help("round")When you are unsure about an argument name, check the “Usage” section in the help page. When you want to see working code, scroll to “Examples.”
Exercise: learn an argument from documentation
- Open
?round. - Find the argument that controls the number of decimal places.
- Run
round(12.3456, digits = 1)and verify the output.
round(12.3456, digits = 1)Reading error messages and debugging mindset
Error messages are signals that something about the code cannot be executed as written. The most productive approach is to read the message, identify the line that caused it, and check object names, parentheses, and expected data types.
Common error patterns to recognize
- Object not found: you used a name that does not exist in the session (often a typo or you didn’t run the line that creates it).
- Unexpected symbol: a syntax issue such as missing commas, quotes, or parentheses.
- Non-numeric argument to a mathematical function: you tried to do math on text.
Practice: trigger and interpret an error
Run this code and read the error carefully. Then fix it by using the correct object name.
total_cost <- 100
# Typo: total_cos does not exist
total_cos + 20Fix:
total_cost + 20Practice: type mismatch
Run the following and observe the message. Then correct it by converting the character to numeric.
price_text <- "19.99"
price_text + 1Fix:
price_num <- as.numeric(price_text)
price_num + 1Core data types: numeric, character, logical
Data types describe what kind of values an object holds. The three foundational types you will use constantly are numeric (numbers), character (text), and logical (TRUE/FALSE). Knowing the type helps you predict what operations are valid.
Numeric
height_cm <- 172.5
class(height_cm)
height_cm * 0.01Character
city <- "Nairobi"
class(city)
# Paste text together
paste("City:", city)Logical
is_adult <- TRUE
class(is_adult)
# Logical comparisons produce TRUE/FALSE
age <- 17
age >= 18Verifiable exercise: predict then check
Before running each line, predict the output type, then verify using class().
a <- 5
b <- "5"
c <- (a == 5)
class(a)
class(b)
class(c)Vectors: the default data structure
A vector is an ordered collection of values of the same basic type. Many R functions expect vectors. You create vectors with c() (combine).
scores <- c(88, 91, 76, 95)
scores
length(scores)
class(scores)Indexing vectors
Use square brackets to select elements by position.
scores[1] # first element
scores[2:3] # second and third
scores[c(1, 4)]Vectorized calculations
R applies many operations element-by-element across vectors.
scores + 5
scores >= 90Exercise: compute a simple summary
Create a vector, compute its mean, and verify the result.
temps_c <- c(18.5, 20.0, 19.2, 21.1)
mean_temp <- mean(temps_c)
mean_tempLists: store mixed types together
A list can hold different types and structures in a single object. Use lists when you need to bundle related items (for example, raw values, a label, and a computed summary) without forcing everything into one type.
scores <- c(88, 91, 76, 95)
report <- list(
student = "Amina",
scores = scores,
average = mean(scores),
passed = mean(scores) >= 60
)
reportAccessing list elements
Use $ for named elements, or [[ ]] for exact element extraction.
report$student
report[["average"]]
report$scores[1:2]Checkpoint mini-script 1: objects, calculations, printing
Write and run this complete mini-script. It creates objects, performs calculations, and prints results. After running, verify that the printed values match your expectations.
# checkpoint-1.R
# Goal: create objects, do simple math, print results
# Inputs
unit_price <- 19.99
quantity <- 3
sales_tax_rate <- 0.07
# Calculations
subtotal <- unit_price * quantity
tax <- subtotal * sales_tax_rate
total <- subtotal + tax
# Output
subtotal
tax
totalCheckpoint mini-script 2: vectors, functions, and clear naming
This script uses a vector and summary functions. Run it top-to-bottom and confirm each printed result.
# checkpoint-2.R
# Goal: work with vectors and summary functions
daily_steps <- c(5200, 8300, 7600, 9100, 4000, 12000, 6800)
steps_mean <- mean(daily_steps)
steps_min <- min(daily_steps)
steps_max <- max(daily_steps)
steps_mean
steps_min
steps_max
days_over_8000 <- daily_steps > 8000
days_over_8000Checkpoint mini-script 3: list-based report with mixed types
This script creates a small “report” object as a list. Run it and inspect elements using both $ and [[ ]].
# checkpoint-3.R
# Goal: bundle related results in a list
expenses <- c(12.50, 8.25, 15.00, 6.75)
expense_report <- list(
category = "Lunch",
expenses = expenses,
count = length(expenses),
total = sum(expenses),
average = mean(expenses),
any_over_10 = any(expenses > 10)
)
expense_report
expense_report$total
expense_report[["any_over_10"]]