Actuarial Data Science - Open Learning Resource
Some coding examples in this lecture are adapted from R for Data Science (Wickham, Çetinkaya-Rundel, and Grolemund 2023).
In practice, a large part of an actuary’s work involves cleaning and reshaping data to ensure that it is trustworthy and easy to analyse.
In this lecture, we introduce a small set of powerful verbs (filter(), select(), mutate(), summarise(), group_by(), and joins) that can be combined to express many common data-wrangling tasks clearly.
dplyr (a core member of tidyverse) for data manipulation and transformation
dplyr overwrites some functions in base R (e.g. filter(), lag()). To use the base versions (after loading dplyr), specify stats::filter() and stats::lag().nycflights13 package, which contains data on flights departing from New York City in 2013ggplot2 to help us explore and understand the data.int: integersdbl: doubles (real numbers)chr: character vectors (strings)dttm: date-times (a date + time)lgl: logical vectors (TRUE or FALSE)fctr: factors (categorical variables with fixed levels)date: dates.These are the common variable types used in tidyverse data frames (tibble)
Functions in the dplyr package:
%>%: pipe operator, used to chain multiple operations togetherglimpse(): a glimpse into the data and its structurefilter(): select observations (rows) that satisfy given conditionsarrange(): reorder rows based on variable valuesselect(): choose a subset of variables (columns)mutate(): create new variables or transform existing onessummarise(): reduce multiple values to a single summarygroup_by(): group data so operations are performed within each groupTo use filter() effectively, you need to know how to select observations using comparison operators. R provides the standard set:
> greater than>= greater than or equal to< less than<= less than or equal to!= not equal to== equal toNote: be cautious when using == with floating point numbers. Consider using near() instead.
filter() are combined with “and”: every condition must be true for a row to be included in the output.Other logical operators:
&: “and”|: “or”!: “not”x %in% y select rows where x is one of the values in yAccording to De Morgan’s laws:
!(x & y) is equivalent to !x | !y!(x | y) is equivalent to !x & !yQuestion:
Find all flights that departed in November or December.
Question:
Find flights that were not delayed (on arrival or departure) by more than two hours.