Chapter 1 Introduction to R

1.1 Learning goals

After this chapter, you should be able to:

  • recognize the R console and basic syntax;
  • create and manipulate vectors, matrices, data frames, and lists;
  • import and export simple data files;
  • write basic functions and produce simple graphics.

1.2 Getting started

The slides introduce R as free software available for Windows, MacOS, and Linux, and present R as both a programming language and a statistical computing environment.

Try this first: type a simple command in R and press Enter.

2 + 4
## [1] 6
sqrt(16)
## [1] 4

1.3 Help, libraries, and the workspace

Useful commands from the slides include help tools, demo files, and library management.

# help("plot")
# demo()
# library()
# search()
Check your understanding

What is the difference between help("plot") and library()?

Answer: help("plot") opens documentation for a specific function, while library() shows or loads installed packages.

1.4 Objects and basic data types

R works with numeric, character, and logical values. It also supports vectors, matrices, data frames, and lists.

x <- 3
is.numeric(x)
## [1] TRUE
as.character(x)
## [1] "3"
as.integer(TRUE)
## [1] 1

In R, many operations are built around objects. Once an object is created, it can be stored, transformed, printed, or reused in later commands.

1.5 Vectors and sequences

Vectors are one-dimensional collections of values. The slides emphasize the use of c(), :, seq(), and rep().

x <- c(1, 4, 9)
y <- c(x, 2, 3)
y
## [1] 1 4 9 2 3
1:4
## [1] 1 2 3 4
seq(1, 4, by = 0.5)
## [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0
rep(1, 4)
## [1] 1 1 1 1
# simple interactive idea: change these values and re-run
start <- 2
end <- 10
step <- 2
seq(start, end, by = step)
## [1]  2  4  6  8 10
Mini exercise

Create a vector containing the first five odd numbers.

One solution: seq(1, 9, by = 2)

1.6 Matrices

Matrices are rectangular arrays of numbers. They can be filled by column or by row.

A <- matrix(c(2, 3, 5, 7, 11, 13), ncol = 2)
B <- matrix(c(2, 3, 5, 7, 11, 13), ncol = 2, byrow = TRUE)
A
##      [,1] [,2]
## [1,]    2    7
## [2,]    3   11
## [3,]    5   13
B
##      [,1] [,2]
## [1,]    2    3
## [2,]    5    7
## [3,]   11   13
# extracting entries
A[, 1]
## [1] 2 3 5
A[2, 2]
## [1] 11

1.7 Data frames

A data frame stores tabular data, often with variables of different types.

students <- data.frame(
  name = c("A", "B", "C"),
  score = c(78, 85, 91),
  passed = c(TRUE, TRUE, TRUE)
)

students
##   name score passed
## 1    A    78   TRUE
## 2    B    85   TRUE
## 3    C    91   TRUE
students$score
## [1] 78 85 91

Edit the values in students and add a new variable called grade.

1.8 Lists

A list can contain objects of different types.

rnd <- list(
  serie = 1:10,
  length = 10,
  type = "arithmetic"
)

names(rnd)
## [1] "serie"  "length" "type"
rnd$length
## [1] 10
rnd[[1]][3]
## [1] 3

1.9 Importing and exporting data

The slides mention scan(), read.table(), write.table(), save(), load(), saveRDS(), and readRDS().

# x <- scan("data.dat")
# tab <- read.table("data.dat", header = TRUE)
# write.table(tab, "output.dat", row.names = FALSE)
# save(tab, file = "tab.rda")
# saveRDS(tab, "tab.rds")

1.10 Functions

Functions help automate repeated tasks.

square_plus_one <- function(x) {
  x^2 + 1
}

square_plus_one(4)
## [1] 17
Try it yourself

Write a function that returns the average of two numbers.

One solution:

avg2 <- function(a, b) {
  (a + b) / 2
}

1.11 Graphics

Basic graphics are essential for exploring data.

x <- 1:10
y <- x^2
plot(x, y, type = "b", main = "A simple quadratic curve")

1.12 Control structures and iterations

Loops and conditional statements allow repeated computation and decision making.

values <- numeric(5)
for (i in 1:5) {
  values[i] <- i^2
}
values
## [1]  1  4  9 16 25
x <- -2
if (x >= 0) {
  "nonnegative"
} else {
  "negative"
}
## [1] "negative"

1.13 Vectorization for probability calculations

R is designed to operate on whole vectors. Vectorized code is usually shorter, clearer, and faster than a loop.

claims <- c(0, 1, 0, 2, 1, 0, 3, 0)

# Which policies generated at least one claim?
claims > 0
## [1] FALSE  TRUE FALSE  TRUE  TRUE FALSE  TRUE FALSE
# Portfolio summaries
sum(claims)
## [1] 7
mean(claims > 0)
## [1] 0.5

Actuarial interpretation: sum(claims) is the aggregate claim count, while mean(claims > 0) is the observed proportion of policies with at least one claim.

1.14 Reproducible simulation

Random-number generators are essential in probability. set.seed() makes an experiment reproducible.

set.seed(211)
sample(1:6, size = 12, replace = TRUE)
##  [1] 4 6 3 5 4 2 5 6 5 5 2 3

Running the chunk again with the same seed gives the same sequence. Changing or removing the seed gives a different sequence.

set.seed(211)
B <- 10000
rolls <- sample(1:6, B, replace = TRUE)
mean(rolls == 6)
## [1] 0.1612
sqrt((1/6) * (5/6) / B)  # theoretical Monte Carlo standard error
## [1] 0.00372678

Simulation error and model error are different. Increasing B reduces simulation error; it does not repair an unrealistic probability model.

1.15 A small probability workflow

The following pattern will recur throughout the course.

set.seed(211)
B <- 50000

# 1. Generate outcomes
x <- rbinom(B, size = 10, prob = 0.03)

# 2. Define the event
large_count <- x >= 2

# 3. Summarize
p_hat <- mean(large_count)
mcse <- sqrt(p_hat * (1 - p_hat) / B)
c(estimate = p_hat, mcse = mcse)
##     estimate         mcse 
## 0.0331200000 0.0008002883

The same three-step structure applies to market-loss events: simulate returns, define a loss threshold, and compute the proportion of simulated returns beyond the threshold.

1.16 Debugging checklist

When code fails or produces an unexpected result, check:

  1. capitalization (mean and Mean are different);
  2. unmatched parentheses or quotation marks;
  3. object names and dimensions (length(), dim(), str());
  4. missing values (is.na() and na.rm = TRUE);
  5. whether a probability argument lies between 0 and 1;
  6. whether the random seed was set before the simulation.

Practice exercises

  1. Create a vector containing claim counts 0, 1, 0, 2, 1, 3. Compute its total, mean, and maximum.
  2. Use sample() to simulate 1,000 fair coin tosses coded as 0 and 1. Estimate the probability of heads.
  3. Write a function mcse(p_hat, B) that returns \(\sqrt{\hat p(1-\hat p)/B}\).
  4. Simulate 20,000 values from a Binomial\((20,0.05)\) distribution and estimate \(\mathbb{P}(X\ge 3)\).
  5. Create a data frame containing policy ID, age, annual premium, and claim indicator for five fictional policies. Use logical indexing to select policies with a claim.
Selected answers
# Exercise 2
set.seed(211)
mean(sample(0:1, 1000, replace = TRUE))

# Exercise 3
mcse <- function(p_hat, B) sqrt(p_hat * (1 - p_hat) / B)

# Exercise 4
set.seed(211)
mean(rbinom(20000, 20, .05) >= 3)

1.17 Chapter summary

In this chapter, you learned how to start working in R, create main object types, explore data structures, use simple functions, and generate basic plots. These tools will be used throughout the probability chapters.