11 R - A Gentle Introduction
11.1 Why R?
R is a free, open-source language for working with data. In a marketing analytics project, you might use it to inspect customer records, calculate campaign summaries, fit a model, and produce a plot. The advantage of writing these steps as code is that you can rerun them when new data arrive—and show a colleague exactly how you obtained a result.
You can run R directly in a console, but an editor such as Positron makes it easier to write scripts, inspect objects, and view plots. This appendix gives you a first, self-contained session. You can type each example into the R console or save all the code in a file ending in .R.
11.2 Your First Data Session
Objects and data frames
An object is a named value that you can use again. We assign a value with <-:
campaign_name <- "Spring promotion"
budget <- 1200
budget / 4Real datasets have many observations. A data frame is a table in which each row represents an observation and each column represents a variable. Let’s create a tiny customer dataset, so every example below works without a download:
customers <- data.frame(
id = c(101, 102, 103, 104, 105),
segment = c("New", "Loyal", "New", "Loyal", "New"),
purchases = c(1, 5, 0, 3, 2),
churned = c(FALSE, FALSE, TRUE, FALSE, TRUE)
)Here churned is a logical variable: each value is either TRUE or FALSE. Before you analyse an unfamiliar data frame, look at its contents and structure:
customers
nrow(customers) # Number of rows
names(customers) # Column names
str(customers) # Column types and sample values
summary(customers$purchases)The $ in customers$purchases selects a column. Because the purchases column is numeric, we can calculate its average with mean(customers$purchases). The average of a logical column is the share of TRUE values, so mean(customers$churned) is the churn rate in this illustrative dataset. In a real project you would first specify when a customer counts as churned and who belongs in the denominator.
Transforming data with dplyr
R’s dplyr package provides verbs for common data operations. Install it once with install.packages("dplyr"), then load it at the beginning of each new R session:
library(dplyr)
filter(customers, purchases > 0) # Keep rows
select(customers, id, segment, churned) # Choose columns
mutate(customers, frequent = purchases >= 3) # Create a columnThe pipe %>% passes the result of one step into the next. For example, we can summarise customer behaviour by segment:
segment_summary <- customers %>%
group_by(segment) %>%
summarise(
n_customers = n(),
churn_rate = mean(churned),
avg_purchases = mean(purchases),
.groups = "drop"
)
segment_summaryRead the code from top to bottom: start with the customers, group by segment, and calculate three statistics for each group. n() counts rows; .groups = "drop" makes the result an ordinary, ungrouped data frame. Check the output: do the group sizes add up to five, and do the means make sense given the original rows?
Change the purchases value for customer 103 and rerun the summary. Which numbers change? Then try filter(customers, segment == "New"). The point is to connect each command to a visible change in the data.
11.3 From an Interactive Session to a Project
Code typed only into the console is easy to lose. Save the commands that create your dataset and summary in analysis.R. If your project folder contains that file, run it from the terminal in the project folder with:
Rscript analysis.RWhen your data come from a file, prefer a relative path within the project, such as data/customers.csv, to a path that only works on your computer. Base R can read a CSV with read.csv("data/customers.csv"). If you prefer read_csv("data/customers.csv"), load the separate readr package (or tidyverse) first. Neither file exists in this self-contained example: create or obtain your own data before running either import command.
Once your steps run reliably as a script, you can combine code, explanations, and results in a Quarto report. For more on variables, loops, functions, and reliable coding habits, return to the Programming Principles chapter.