Full text
Statistical Computing and Programming Vik Gopal, Daisy Pham Thi Kim Cuc 2025-12-22
Contents Contents 2 List of Figures 9 Preface 13 1 Introduction to R 15 1.1 Introduction...................................... 15 1.2 InstallingRandRstudio............................... 15 1.3 Basic Data Structures in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.4 Creating Basic Objects in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.4.1 Vectors .................................... 17 1.4.2 Matrices.................................... 19 1.4.3 Dataframes .................................. 20 1.4.4 Lists...................................... 22 1.5 ReadingDataintoR................................. 23 1.6 Accessing Parts of Dataframes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 1.7 LoopsinR ...................................... 26 1.7.1 WhileLoops ................................. 27 1.7.2 ForLoops................................... 27 1.8 RedirectingROutput ................................ 28 1.9 User-Defined Functions in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 1.10Miscellaneous..................................... 29 1.10.1GettingHelp ................................. 29 1.11InstallingPackages.................................. 30 1.12FurtherReadings................................... 30 1.13 Heads-Up on Differences with Python . . . . . . . . . . . . . . . . . . . . . . . 31 1.14References....................................... 31 1.14.1WebsiteReferences.............................. 31 2
1.15Exercises ....................................... 31 2 Introduction to Python 33 2.1 Introduction...................................... 33 2.2 Installing Python and Jupyter Lab . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.3 Basic Data Structures in Python . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.4 Slice Operator in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 2.5 NumpyArrays .................................... 37 2.6 PandasDataFrames ................................. 38 2.7 Reading Data into Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 2.8 Subsetting DataFrames with Pandas . . . . . . . . . . . . . . . . . . . . . . . . 40 2.9 LoopsinPython ................................... 41 2.10UserDefinedFunctions ............................... 43 2.11Miscellaneous..................................... 43 2.11.1 Package installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 2.11.2Gettinghelp ................................. 43 2.12 Major Differences with R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2.13References....................................... 44 2.13.1WebsiteReferences.............................. 44 2.14Exercises ....................................... 44 3 Exploring Quantitative Data 45 3.1 Introduction...................................... 45 3.2 NumericalSummaries ................................ 47 3.3 GraphicalSummaries................................. 50 3.3.1 Histograms .................................. 50 3.3.2 DensityPlots................................. 54 3.3.3 Boxplots.................................... 56 3.3.4 QQ-plots ................................... 58 3.4 Correlation ...................................... 61 3.5 ScatterplotMatrices ................................. 63 3.6 References....................................... 66 3.6.1 WebsiteReferences.............................. 66 3.7 Exercises ....................................... 66 3
4 Exploring Categorical Data 67 4.1 Introduction...................................... 67 4.2 ContingencyTables.................................. 67 4.3 Visualisations..................................... 68 4.3.1 Barcharts................................... 68 4.3.2 Mosaicplots ................................. 70 4.3.3 Conditional Density Plots . . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.4 TestsforIndependence................................ 73 4.4.1 π2-Test for Independence . . . . . . . . . . . . . . . . . . . . . . . . . . 74 4.4.2 FisherβsExactTest.............................. 77 4.4.3 π2-Test for πΓπTables ........................... 79 4.5 MeasuresofAssociation ............................... 80 4.5.1 OddsRatio .................................. 80 4.5.2 For Ordinal Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 4.6 Furtherreadings ................................... 83 4.7 References....................................... 84 4.7.1 WebsiteReferences.............................. 84 4.8 Exercises ....................................... 84 5 Robust Statistics 85 5.1 Introduction...................................... 85 5.2 Notation........................................ 85 5.3 Datasets........................................ 86 5.4 AssessingRobustness................................. 87 5.4.1 Asymptotic Relative Eο¬iciency . . . . . . . . . . . . . . . . . . . . . . . 88 5.5 Requirements of Robust Summaries . . . . . . . . . . . . . . . . . . . . . . . . 89 5.6 MeasuresofLocation................................. 89 5.6.1 M-estimators ................................. 89 5.6.2 Trimmedmean................................ 91 5.6.3 WinsorisedMean............................... 91 5.7 MeasuresofScale................................... 92 5.7.1 Sample Standard Deviation . . . . . . . . . . . . . . . . . . . . . . . . . 92 5.7.2 Median Absolute Deviation . . . . . . . . . . . . . . . . . . . . . . . . . 92 5.7.3 InterquartileRange.............................. 93 4
5.8 Examples ....................................... 94 5.9 Summary ....................................... 95 5.10References....................................... 96 5.10.1WebsiteReferences.............................. 96 5.11Exercises ....................................... 96 6 Introduction to SAS 97 6.1 Introduction...................................... 97 6.2 Registering for a SAS Studio Account . . . . . . . . . . . . . . . . . . . . . . . 97 6.3 An Overview of SAS Language . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 6.4 Basic Rules for SAS Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 6.4.1 ForSASstatements ............................. 99 6.4.2 ForSASnames................................ 100 6.4.3 ForSASvariables .............................. 100 6.5 ReadingDataintoSAS ............................... 100 6.6 Uploading and Using Datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 6.7 Summarising Numerical Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 6.7.1 Numerical Summaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 6.7.2 ScatterPlots ................................. 103 6.7.3 Histograms .................................. 104 6.7.4 Boxplots.................................... 105 6.7.5 QQ-plots ................................... 107 6.8 CategoricalData ................................... 107 6.9 References....................................... 109 6.10WebsiteReferences.................................. 109 7 Two-sample Hypothesis Tests 110 7.1 Introduction...................................... 110 7.2 Procedure for Significance Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.2.1 Step 1: Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.2.2 Step 2: State the hypotheses and significance level . . . . . . . . . . . . 110 7.2.3 Step 3: Compute the test statistic . . . . . . . . . . . . . . . . . . . . . 111 7.2.4 Step 4: Compute the π-value ........................ 111 7.2.5 Step 5: State your conclusion . . . . . . . . . . . . . . . . . . . . . . . . 112 7.3 ConfidenceIntervals ................................. 112 5
7.4 ParametricTests ................................... 112 7.4.1 Independent Samples Test . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.4.2 More on Assessing Normality . . . . . . . . . . . . . . . . . . . . . . . . 118 7.4.3 PairedSampleTest.............................. 120 7.5 Non-parametricTests ................................ 123 7.5.1 Independent Samples Test . . . . . . . . . . . . . . . . . . . . . . . . . . 123 7.5.2 Paired Samples Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 7.6 Summary ....................................... 128 7.7 References....................................... 128 7.7.1 WebsiteReferences.............................. 128 7.8 Exercises ....................................... 128 8 ANOVA 129 8.1 Introduction...................................... 129 8.2 One-Way Analysis of Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 8.2.1 FormalSet-up ................................ 131 8.2.2 πΉ-Test in One-Way ANOVA . . . . . . . . . . . . . . . . . . . . . . . . 132 8.2.3 Assumptions ................................. 132 8.3 Comparing specific groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 8.4 ContrastEstimation ................................. 139 8.5 MultipleComparisons ................................ 141 8.5.1 Bonferroni................................... 142 8.5.2 TukeyHSD .................................. 142 8.6 Kruskal-Wallis Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 8.6.1 FormalSet-up ................................ 144 8.7 Summary ....................................... 145 8.8 References....................................... 146 8.8.1 WebsiteReferences.............................. 146 8.8.2 Exercises ................................... 146 9 Linear Regression 147 9.1 Introduction...................................... 147 9.2 Simple Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.2.1 FormalSet-up ................................ 149 9.2.2 Estimation .................................. 149 6
9.3 Hypothesis Test for Model Significance . . . . . . . . . . . . . . . . . . . . . . . 151 9.3.1 Coeο¬icient of Determination, π
2...................... 152 9.4 Multiple Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 9.4.1 FormalSetup................................. 160 9.4.2 Estimation .................................. 160 9.4.3 Coeο¬icient of Determination, π
2...................... 161 9.4.4 HypothesisTests............................... 161 9.5 IndicatorVariables.................................. 164 9.5.1 Including a Categorical Variable . . . . . . . . . . . . . . . . . . . . . . 164 9.6 Interactionterm ................................... 168 9.7 ResidualDiagnostics................................. 172 9.7.1 Standardised Residuals . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 9.7.2 Normality................................... 173 9.7.3 Scatterplots.................................. 174 9.7.4 InfluentialPoints............................... 176 9.8 FurtherReading ................................... 177 9.9 References....................................... 179 9.9.1 WebsiteReferences.............................. 179 9.10Exercises ....................................... 179 10 Simulation 180 10.1Introduction...................................... 180 10.2Theory......................................... 181 10.3 Generating Random Variables in R and Python . . . . . . . . . . . . . . . . . . 182 10.4 Monte-Carlo Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 10.5SimulationStudies .................................. 186 10.5.1 Confidence Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 10.5.2TypeIError ................................. 187 10.5.3 Newspaper Inventory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 10.6ResamplingMethods................................. 189 10.6.1PermutationTest............................... 189 10.6.2Bootstrapping ................................ 191 10.7Summary ....................................... 192 7
10.8References....................................... 192 10.8.1 Website References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 10.9Exercises ....................................... 193 Academic References 194 8
List of Figures 1.1 R: Base R GUI .................................... 16 1.2 R: Rstudio interface ................................. 17 2.1 Py: JupyterLab interface .............................. 34 2.2 Py: Positive and negative indexing ......................... 37 3.1 Data types ...................................... 45 3.2 Three vastly different datasets, all with mean 0 and s.d. 1 ............ 50 3.3 Histogram with outliers ............................... 51 3.4 Bimodal histogram .................................. 51 3.5 Skewed histograms .................................. 51 3.6 R: Histogram of G3 scores .............................. 52 3.7 Py: Histogram of G3 scores ............................. 52 3.8 R: Lattice plot of G3 scores by Medu ........................ 53 3.9 Py: Lattice plot of G3 scores by Medu ....................... 54 3.10 R: Estimated densities for G3 scores, by Medu .................. 55 3.11 Py: Estimated densities for G3 scores, by Medu .................. 55 3.12 Boxplot construction ................................. 56 3.13 R: Boxplot of G3 scores, by gout variable ..................... 57 3.14 Py: Boxplot of G3 scores, by gout variable ..................... 58 3.15 QQ-plots ....................................... 58 3.16 Comparing data with reference Normal (blue) ................... 60 3.17 R: QQ plot for compressive strength ........................ 60 3.18 Py: QQ plot for compressive strength ....................... 61 3.19 Varying linear relations and corresponding π-values ................ 62 3.20 Non-linear relations and corresponding π-values .................. 62 3.21 R: Scatterplot matrix for concrete dataset ..................... 63 3.22 Py: Scatterplot matrix for concrete dataset .................... 64 3.23 R: Heatmap of correlation matrix for concrete data ................ 65 9
Figure 1.1: R: Base R GUI The installation file for RStudio can be obtained from this URL. It is updated a couple of times a year. Make sure you have at least version 2025.09.x for our course. Hereβs a quick orientation of the panels in Rstudio, with reference to Figure 1.2. β’ Panel 1 is the console. βThis is where you type R commands. βThe output from these commands or functions will also be seen here. βUse the βkey to scroll through previously entered commands. β’ Panel 2 contains the History and Environment tabs. βThe History tab displays all commands that have been previously entered in the current session. βThese commands can be sent directly to the source code panel or the console panel. βThe Environment tab in this panel has a list of items that have been created in the current session. β’ Panel 3 contains the Files,Plots and Help tabs. βThe Files tab contains a directory structure that allows one to choose and open files in the source code editor. βThrough the Plots tab, one can access all plots that have been created in the current session. βThe Help tab displays the documentation for R functions. β’ Panel 4 contains the source code editor. βThis where you edit R scripts. 16
Figure 1.2: R: Rstudio interface βYou can hit Ctrl-Enter to execute a command (in the console panel) while your cursor is in the source code panel. βYou can also highlight code and the editor and execute it directly in the console panel. 1.3 Basic Data Structures in R Probably the four most frequently used data structures in R are the following: β’Vector: A set of elements of the same mode (logical; numeric; character; factor). β’Matrix: A set of elements appearing in rows and columns, where the elements are of the same mode. β’Dataframe: This is similar to the matrix object in that it is 2-dimensional. However, columns in a dataframe can have different modes. Rows typically contain different observations from your study or measurements from your experiment. The columns contain the values of different variables which may be of different modes. β’List: A list is a generalization of a vector β it represents a collection of data objects. 1.4 Creating Basic Objects in R 1.4.1 Vectors To create a vector in R, the simplest way is to use the combine function c(). 17
#creating a vector of numbers: numeric_vec <- c(2,4,6,8,10) numeric_vec [1] 2 4 6 8 10 # creating a vector of strings/characters: string_vec <-c("weight","height","gender") string_vec [1] "weight" "height" "gender" # creating a Boolean vector (T/F): logical_vec <- c(TRUE,TRUE,FALSE) logical_vec [1] TRUE TRUE FALSE # creating factors: factors_vec <- factor(c("male","male","female")) factors_vec [1] male male female Levels: female male Factors are slightly different from strings. In R, they are used to represent categorical variables in linear models. When we need to create a vector that defines groups (of Females followed by Males, for instance), we can turn to a convenient function called rep(). This function replicates elements of vectors and lists. The syntax is as follows: rep(a, b) will replicate the item a,btimes. Here are some examples: r1 <- rep(2,3) r1 [1] 2 2 2 r2 <- rep(c(1,2),3) r2 [1] 1 2 1 2 1 2 r3 <- rep(c(6,3),c(2,4)) r3 [1] 6 6 3 3 3 3 18
r4 <- rep(string_vec, 2) r4 [1] "weight" "height" "gender" "weight" "height" "gender" On other occasions, we may need to create an index vector, along the rows of a dataset. The seq() function is useful for this purpose. It creates a sequence of numbers that are evenly spread out. seq(from=2,to=10,by=2) [1] 2 4 6 8 10 seq(from=2,to=10,length = 5) [1] 2 4 6 8 10 seq(2,5,0.8) [1] 2.0 2.8 3.6 4.4 seq(2,5,0.8)*2 [1] 4.0 5.6 7.2 8.8 The final example above, where the sequence vector of length 4 is multiplied by a scalar 2, is an example of the recycling rule in R β the shorter vector is recycled to match the length of the longer one. This rule applies within all built-in R functions. Try to use this rule to your advantage when using R. If you only need to create a vector of integers that increase by 1, you do not even need seq(). The :colon operator will handle the task. s1 <- 2:5 s1 [1] 2 3 4 5 1.4.2 Matrices Thus far, we have been creating vectors. Matrices are higher dimensional objects. To create a matrix, we use the matrix() function. The syntax is as follows: matrix(v,r,c) will take the values from vector vand create a matrix with rrows and ccolumns. R is column-major, which means that, by default, the matrix is filled column-by-column, not row-by-row. 19
v <- c(1:6) m1 <- matrix(v, nrow=2,ncol=3) m1 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 m2 <- matrix(v, nrow=2,ncol=3,byrow=TRUE) m2 [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 New rows (or columns) can be added to an existing matrix using the command rbind() (resp. cbind()). a <- c(1,2,3,4) b <- c(5,6,7,8) ab_row <- rbind(a,b) ab_row [,1] [,2] [,3] [,4] a 1 2 3 4 b 5 6 7 8 ab_col <- cbind(m1, c(7,8)) ab_col [,1] [,2] [,3] [,4] [1,] 1 3 5 7 [2,] 2 4 6 8 1.4.3 Dataframes Now letβs turn to dataframes, which are the most common object we are going to use for storing data in R. A dataframe is a tabular object, like a matrix, but the columns can be of different types; some can be numeric and some can be character, for instance. Think of a dataframe as an object with rows and columns: β’ The rows contain different observations or measurements; β’ The columns contain the values of different variables. As a general guideline, we should try to store our data in a format where a single variable is not spread across columns. 20
Example 1.1 (Tidy Data).Consider an experiment where there are three treatments (control, pre-heated and pre-chilled), and two measurements per treatment. The response variable is store in the following dataframe: Control Pre_heated Pre_chilled 6.1 6.3 7.1 5.9 6.2 8.2 The above format is probably convenient for recording data. However, the response variable has been spread across three columns. The tidy version of the dataset is: Response Treatment 6.1 control 5.9 control 6.3 pre_heated 6.2 pre_heated 7.1 pre_chilled 8.2 pre_chilled The second version is more amenable to computing conditional summaries, making plots and for modeling in R. Dataframes can be created from matrices, and they can also be created from individual vectors. The function as.data.frame() converts a matrix into a dataframe, with generic column names assigned. df1 <- as.data.frame(m1) df1 V1 V2 V3 1 1 3 5 2 2 4 6 If we intend to pack individual vectors into a dataframe, we use the function data.frame(). We can also specify custom column names when we call this function. a <- c(11,12) b <- c(13,14) df2 <- data.frame(col1 = a, col2 = b) df2 col1 col2 1 11 13 2 12 14 21
1.4.4 Lists Finally, we turn to lists. You can think of a list in R as a very general basket of objects. The objects do not have to be of the same type or length. The objects can be lists themselves. Lists are created using the list( ) function; elements within a list are accessed using the $notation, or by using the names of the elements in the list. ls1 <- list(A=seq(1,5,by=2), B=seq(1,5,length=4)) ls1 $A [1] 1 3 5 $B [1] 1.000000 2.333333 3.666667 5.000000 ls1[[2]] [1] 1.000000 2.333333 3.666667 5.000000 ls1[["B"]] [1] 1.000000 2.333333 3.666667 5.000000 ls1$A [1] 1 3 5 Example 1.2 (Extracting π-values).The iris dataset is a very famous dataset that comes with R. It contains measurements on the flowers of three different species. Let us conduct a 2-sample π‘-test, and extract the π-value. setosa <- iris$Sepal.Length[iris$Species == "setosa"] virginica <- iris$Sepal.Length[iris$Species == "virginica"] t_test_out <- t.test(setosa, virginica) str(t_test_out) List of 10 $ statistic : Named num -15.4 ..- attr(*, "names")= chr "t" $ parameter : Named num 76.5 ..- attr(*, "names")= chr "df" $ p.value : num 3.97e-25 $ conf.int : num [1:2] -1.79 -1.38 ..- attr(*, "conf.level")= num 0.95 $ estimate : Named num [1:2] 5.01 6.59 22
..- attr(*, "names")= chr [1:2] "mean of x" "mean of y" $ null.value : Named num 0 ..- attr(*, "names")= chr "difference in means" $ stderr : num 0.103 $ alternative: chr "two.sided" $ method : chr "Welch Two Sample t-test" $ data.name : chr "setosa and virginica" - attr(*, "class")= chr "htest" str( ) prints the structure of an R object. From the output above, we can tell that the output object is a list with 10 elements. The particular element we need to extract is p.value. t_test_out$p.value [1] 3.966867e-25 1.5 Reading Data into R It is uncommon that we will be creating dataframes by hand, as we have been doing so far. It is more likely that we will be reading in a dataset from a file in order to perform analysis on it. Thus, at this point, letβs sidetrack a little and discuss how we can read data into R as a dataframe. The two most common functions for this purpose are read.table() and read.csv(). The former is used when our data is contained in a text file, with spaces or tabs separating columns. The latter function is for reading in files with comma-separated-values. If our data is stored as a text file, it is always a good idea to open it and inspect it before getting R to read it in. Text files can be opened with any text editor; csv files can also be opened by Microsoft Excel. When we do so, we should look out for a few things: β’ Are there column names in the first row, or does the data actually begin in line 1? β’ Is it spaces or commas that separate columns? β’ Are there trailing values in the last few lines of the file? The file crab.txt contains measurements on crabs. If you open up the file outside of R, you should observe that the first line of the file contains column names. By the way, head() is a convenient function for inspecting the first few rows of a dataframe. There is a similar function tail() for inspecting the last few rows. data1 <- read.table("data/crab.txt") head(data1) V1 V2 V3 V4 V5 1 color spine width satell weight 2 3 3 28.3 8 3.050 3 4 3 22.5 0 1.550 4 2 1 26.0 9 2.300 5 4 3 24.8 0 2.100 6 4 3 26.0 4 2.600 23
The data has not been read in correctly. To fix this, we need to inform R that the first row functions as the column names/headings. data1 <- read.table("data/crab.txt",header=TRUE) head(data1) color spine width satell weight 1 3 3 28.3 8 3.05 2 4 3 22.5 0 1.55 3 2 1 26.0 9 2.30 4 4 3 24.8 0 2.10 5 4 3 26.0 4 2.60 6 3 3 23.8 0 2.10 If the first line of the data file does not contain the names of the variables, we can create a vector beforehand to store and then use the names. varnames <- c("Subject","Gender","CA1","CA2","HW") data2 <- read.table("data/ex_1.txt",header = FALSE, col.names = varnames) data2 Subject Gender CA1 CA2 HW 1 10 M 80 84 A 2 7 M 85 89 A 3 4 F 90 86 B 4 20 M 82 85 B 5 25 F 94 94 A 6 14 F 88 84 C The use of read.csv() is very similar, but it is applicable when the fields within each line of the input file are separated by commas instead of tabs or spaces. data3 <- read.csv("data/ex_1_comma.txt",header = FALSE) data3 V1 V2 V3 V4 V5 1 10 M 80 84 A 2 7 M 85 89 A 3 4 F 90 86 B 4 20 M 82 85 B 5 25 F 94 94 A 6 14 F 88 84 C 24
1.6 Accessing Parts of Dataframes We now turn to the task of accessing a subset of rows and/or columns of a dataframe. The notation uses rectangular brackets, along with a comma inside these brackets to demarcate the row and column specifiers. To access all rows from a particular set of columns, we leave the row column specification empty. data3[, 2:4] V2 V3 V4 1 M 80 84 2 M 85 89 3 F 90 86 4 M 82 85 5 F 94 94 6 F 88 84 To retrieve a subset of rows, we use the space before the comma. data3[1:3, ] V1 V2 V3 V4 V5 1 10 M 80 84 A 2 7 M 85 89 A 3 4 F 90 86 B In R, dataframes are special kinds of lists. Hence, individual columns can be retrieved from a dataframe (as a vector) using the $operator. These columns can then be used to retrieve only the rows that satisfy certain conditions. In order to achieve this task, we turn to logical vectors. The following code returns only the rows corresponding to Gender equal to βMβ. data2[data2$Gender == "M", ] Subject Gender CA1 CA2 HW 1 10 M 80 84 A 2 7 M 85 89 A 4 20 M 82 85 B Logical vectors contain TRUE/FALSE values in their components. These vectors can be combined with &(AND) and |(OR) operations to yield only the rows that satisfy all conditions. Below, we return all rows where Gender is equal to βMβ and CA2 is greater than 85. data2[data2$Gender == "M" &data2$CA2 >85, ] Subject Gender CA1 CA2 HW 2 7 M 85 89 A 25
data2[data2$Gender == "M" && data2$CA2 >85, ] 32
2 Introduction to Python 2.1 Introduction Python is a general-purpose programming language. It is a higher-level language than C, C++ and Java in the sense that a Python program does not have to be compiled before execution. It was originally conceived back in the 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. The language is named after a BBC TV show (Guidoβs favorite program) βMonty Pythonβs Flying Circusβ, not the snake! Python reached version 1.0 in January 1994. Python 2.0 was released on October 16, 2000. Python 3.0, which is backwards-incompatible with earlier versions, was released on 3 December 2008. Python is a very flexible language; it is simple to learn yet is fast enough to be used in production. Over the past ten years, more and more comprehensive data science toolkits (e.g. scikit-learn, NLTK, tensorflow, keras) have been written in Python and are now the standard frameworks for those models. Just like R, Python is an open-source software. It is free to use and extend. 2.2 Installing Python and Jupyter Lab To install Python, navigate to the oο¬icial Python download page to obtain the appropriate installer for your operating system. ΔΊImportant For our class, please ensure that you are using at least Python 3.12, and that you have installed the package versions in requirements.txt. The next step is to create a virtual environment for this course. Virtual environments are specific to Python. They allow you to retain multiple versions of Python, and of packages, on the same computer. Go through the videos on Canvas relevant to your operating system to create a virtual environment and install Jupyter Lab on your machine. Jupyter notebooks are great for interactive work with Python, but more advanced users may prefer a full-fledged IDE. If you are an advanced user, and are comfortable with an IDE of your own choice (e.g. Spyder or VSCode), feel free to continue using that to run the codes for this course. 33
ΔΊImportant Even if you are using Anaconda/Spyder/VSCode, you still need to create a virtual environment, and you still need to install packages using the requirements.txt file. Jupyter notebooks consist of cells, which can be of three main types: β’ code cells, β’ output cells, and β’ markdown cells. Figure 2.1: Py: JupyterLab interface In Figure 2.1, the red box labelled 1 is a markdown cell. It can be used to contain descriptions or summary of the code. The cells in the box labelled 2 are code cells. To run the codes from our notes, you can copy and paste the codes into a new cell, and then execute them with Ctrl-Enter. Try out this Easter egg that comes with any Python installation: import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. 34
Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! More information on using Jupyter notebooks can be obtained from this link. 2.3 Basic Data Structures in Python The main objects in native1Python that contain data are β’Lists, which are defined with [ ]. Lists are mutable. β’Tuples, which are defined with ( ). Tuples are immutable. β’Dictionaries, which are defined with { }. Dictionaries have keys and items. They are also mutable. Very soon, we shall see that for statistics, the more common objects we shall deal with are dataframes (from pandas) and arrays (from numpy). However, the latter two require add-on packages; the three object classes listed above are baked into Python. Here is how we create lists, tuples and dictionaries. Elements in lists and tuples can be accessed using a square bracket notation, just like in R. x_list =[1,2,3] x_tuple =(1,2,3) x_dict ={'a':1,'b':2,'c':3}# access with x_dict['a'] Suppose we have the following list: x=[1,3,5,7,8,9,10] The following assignment is OK, because xis a list, and hence mutable. x[3]=17 print(x) 1i.e., Python without any packages imported. 35
[1, 3, 5, 17, 8, 9, 10] However, the following will return an error, because x_tuple is a tuple, and hence immutable. x_tuple =(1,3,5,6,8,9,10) x_tuple[3]=17 ΔΉNote Note that we do not need the c( ) function, like we did in R. This is a common mistake when switching between the two languages. 2.4 Slice Operator in Python One important point to take note is that, in contrast to R, Python indexes objects starting with 0. Second, the slice operator in Python is a little more powerful than in R. It can be used to extract regular sequences from a list, tuple or string easily. In general, the syntax is <list-like object>[a:b], where aand bare integers. Such a call would return the elements at indices a,a+1 until b-1. Take note that the end point index is not included. char_list =['P','y','t','h','o','n'] char_list[0]# returns first element 'P' char_list[-1]# returns last element 'n' len(char_list) # returns number of elements in list-like object. 6 char_list[::2]# from first to last, every 2 apart. ['P', 't', 'o'] This indexing syntax is used in the additional packages we are going to use as well, so it is good to know about it. Take note that in Python, a negative index does not correspond to the element being dropped; it corresponds to counting from the end of the array-like object. Figure 2.2 displays a pictorial representation of how positive and negative indexes work together. 36
Figure 2.2: Py: Positive and negative indexing 2.5 Numpy Arrays Just like R, Python has several contributed packages that are essential for statistics and data analysis. These include numpy and pandas. These correct versions of these packages would have been installed if you had used the provided requirements file. import numpy as np array1 =np.array([1,2,3,4,5]) array2 =np.array([6,7,8,9,10]) matrix1 =np.array([array1, array2]) print(matrix1) [[ 1 2 3 4 5] [ 6 7 8 9 10]] The slice operator can then be used in each dimension of the matrix to subset it. matrix1[0,0::3]# returns first row, columns 1 and 4 array([1, 4]) matrix1[1,1:3]# returns second row, columns 2 and 3 array([7, 8]) The numpy arrays are objects in Python, with several attributes and methods associated with them. Here are a couple of attributes: # To obtain the dimensions of an array: matrix1.shape (2, 5) # To transpose a 2-D array matrix1.T 37
array([[ 1, 6], [ 2, 7], [ 3, 8], [ 4, 9], [ 5, 10]]) Here is a table with some common methods associated with numpy arrays. The objects referred to in the second column are from the earlier lines of code. Method Description mean Computes col- or row-wise means, e.g. matrix1.mean(axis=0) or matrix1.mean(axis=1) sum Computes col- or row-wise means, e.g. matrix1.sum(axis=0) or matrix1.sum(axis=1) argmax Return the index corresponding to the max within the specified dimension, e.g. matrix1.argmax(axis=0) for the position with the max within each column. reshape To change the dimensions, e.g. array1.reshape((5,1)) converts the array into a 5x1 matrix To combine arrays, we use the functions vstack and hstack. These are analogous to rbind and cbind in R. np.vstack([matrix1, array1]) array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [ 1, 2, 3, 4, 5]]) np.hstack([array1.reshape((5,1)), array2.reshape((5,1)), matrix1.T]) array([[ 1, 6, 1, 6], [ 2, 7, 2, 7], [ 3, 8, 3, 8], [ 4, 9, 4, 9], [ 5, 10, 5, 10]]) 2.6 Pandas DataFrames The next important add-on package that we shall work with is pandas. It provides a DataFrame class of objects for working with tabular data, just like data.frame within R. However, there are some syntactic differences with R that we shall soon get to. The following command creates a simple pandas dataframe. 38
import pandas as pd data ={'X': [1,2,3,4,5,6], 'Y': [6,5,4,3,2,1]} df =pd.DataFrame(data, columns =['X','Y']) print(df) X Y 0 1 6 1 2 5 2 3 4 3 4 3 4 5 2 5 6 1 We will get into the syntax for accessing subsets of the dataframe soon, but for now, here is how we can extract a single column from the dataframe. The resulting object is a pandas Series, which is a lot like a 1-D array, and can be indexed like one as well. col_x =df.X col_x[0:3] 0 1 1 2 2 3 Name: X, dtype: int64 ΔΉNote The built-in objects in Python are lists, tuples and dictionaries. Lists and tuples can contain elements of different types, e.g. strings and integers in a single object. However, they have no dimensions, so to speak of. Numpy arrays can be high-dimensional structures. In addition, the elements have to be homogeneous. For instance, in a 2x2x2 numeric numpy array, every one of the 8 elements has to be a float point number. Pandas DataFrames are tabular objects, where, within a column, each element has to be of the same type. 2.7 Reading Data into Python Let us begin with the same file that we began with in the topic on R: crab.txt. In Section 1.5, we observed that this file contained headings, and that the columns were separated by spaces. The pandas function to read in such text files is read_table(). It has numerous optional arguments, but in this case we just need these two: data1 =pd.read_table('data/crab.txt', header=0, sep="\\s+") data1.head() 39
color spine width satell weight 0 3 3 28.3 8 3.05 1 4 3 22.5 0 1.55 2 2 1 26.0 9 2.30 3 4 3 24.8 0 2.10 4 4 3 26.0 4 2.60 Do take note of the differences with R - the input to the header argument corresponds to the line number containing the column names. Secondly, the head() function is a method belonging to the DataFrame object. When the file does not contain column names, we can supply them (as a list or numpy array) when we read the data in. Here is an example: varnames =["Subject","Gender","CA1","CA2","HW"] data2 =pd.read_table('data/ex_1.txt', header=None, names=varnames, sep="\\s+") data2 Subject Gender CA1 CA2 HW 0 10 M 80 84 A 1 7 M 85 89 A 2 4 F 90 86 B 3 20 M 82 85 B 4 25 F 94 94 A 5 14 F 88 84 C 2.8 Subsetting DataFrames with Pandas DataFrames in pandas are indexed for eο¬icient searching and retrieval. When subsetting them, we have to add either .loc or .iloc and use it with square brackets. The .loc notation is used when we wish to index rows and columns according to their names. The general syntax is <DataFrame>.loc[ , ]. A slice operator can be used separately for the row subset and the column subset to be retrieved. For instance, to retrieve rows 0,1,2 and columns from color to width: data1.loc[0:2,'color':'width'] color spine width 0 3 3 28.3 1 4 3 22.5 2 2 1 26.0 To retrieve every second row starting from row 0 until row 5, and all columns: 40
data1.loc[0:5:2, ] color spine width satell weight 0 3 3 28.3 8 3.05 2 2 1 26.0 9 2.30 4 4 3 26.0 4 2.60 The .iloc notation is used when we wish to index rows and columns using integer values. The general syntax is similar; try this and observe the difference with .loc. data1.iloc[0:2,0:2] color spine 033 143 If you notice, the .iloc notation respects the rules of the in-built slice operator, in the sense that the end point is not included in the output. On the other hand, the .loc notation includes the end point. In data analysis, a common requirement is to subset a dataframe according to values in columns. Just like in R, this is achieved with logical values. data2[data2.Gender == "M"] Subject Gender CA1 CA2 HW 0 10 M 80 84 A 1 7 M 85 89 A 3 20 M 82 85 B data2[(data2.Gender == "M")&(data2.CA2 >85)] Subject Gender CA1 CA2 HW 1 7 M 85 89 A 2.9 Loops in Python It is extremely eο¬icient to execute βforβ loops in Python. Many objects in Python are iterators, which means they can be iterated over. Lists, tuples and dictionaries can all be iterated over very easily. Before getting down to examples, take note that Python does not use curly braces to denote code blocks. Instead, these are defined by the number of indentations in a line. for iin x[:2]: print(f"The current element is {i}.") 41
stud_perf <- read.table("data/student/student-mat.csv",sep=";", header=TRUE) summary(stud_perf$G3) Min. 1st Qu. Median Mean 3rd Qu. Max. 0.00 8.00 11.00 10.42 14.00 20.00 sum(is.na(stud_perf$G3)) [1] 0 Python code import pandas as pd import numpy as np stud_perf =pd.read_csv("data/student/student-mat.csv", delimiter=";") stud_perf.G3.describe() count 395.000000 mean 10.415190 std 4.581443 min 0.000000 25% 8.000000 50% 11.000000 75% 14.000000 max 20.000000 Name: G3, dtype: float64 #stud_perf.G3.info() From the output, we can understand that we have 395 observations, ranging from 0 to 20. I would surmise that the data is more or less symmetric in the middle (distance from 3rd-quartile to median is identical to distance from median to 1st-quartile). There are no missing values in the data. However, summaries of a single variable are rarely useful since we do not have a basis for comparison. In this dataset, we are interested in how the grade varies with one or some of the other variables. Letβs begin with Motherβs education. R code round(aggregate(G3 ~Medu, data=stud_perf, FUN=summary), 2) 48
Medu G3.Min. G3.1st Qu. G3.Median G3.Mean G3.3rd Qu. G3.Max. 1 0 9.00 12.00 15.00 13.00 15.00 15.00 2 1 0.00 7.50 10.00 8.68 11.00 16.00 3 2 0.00 8.00 11.00 9.73 13.00 19.00 4 3 0.00 8.00 10.00 10.30 13.00 19.00 5 4 0.00 9.50 12.00 11.76 15.00 20.00 table(stud_perf$Medu) 01234 3 59 103 99 131 Python code stud_perf[['Medu','G3']].groupby('Medu').describe() G3 count mean std min 25% 50% 75% max Medu 0 3.0 13.000000 3.464102 9.0 12.0 15.0 15.0 15.0 1 59.0 8.677966 4.364594 0.0 7.5 10.0 11.0 16.0 2 103.0 9.728155 4.636163 0.0 8.0 11.0 13.0 19.0 3 99.0 10.303030 4.623486 0.0 8.0 10.0 13.0 19.0 4 131.0 11.763359 4.267646 0.0 9.5 12.0 15.0 20.0 Now we begin to understand the context of G3 a little better. As the education level of the mother increases, the mean does increase. The middle 50-percent of the grade does seem to increase as well. The exception is the case where the mother has no education, but we can see that there are only 3 observations in that category, so we should not read too much into it. Here are some things to note about numerical summaries: β’ If the mean and the median are close to each other, it indicates that the distribution of the data is close to symmetric. β’ The mean is sensitive outliers but the median is not. We shall see more about this in Section 5.1. β’ When the mean is much larger than the median, it suggests that there could be a few very large observations. It has resulted in a right-skewed distribution. Conversely, if the mean is much smaller than the median, we probably have a left-skewed distribution. While numerical summaries provide us with some basic information about the data, they also leave out a lot. Even for experts, it is possible to have a wrong mental idea about the data from the numerical summaries alone. For instance, all three histograms in Figure 3.2 have a mean of 0 and standard deviation of 1! Thatβs why we have to turn to graphics as well, in order to summarise our data. 49
Figure 3.2: Three vastly different datasets, all with mean 0 and s.d. 1 3.3 Graphical Summaries 3.3.1 Histograms The first chart type we shall consider is a histogram. A histogram is a graph that uses bars to portray the frequencies or relative frequencies of the possible outcomes for a quantitative variable. When we create a histogram, here are some things that we look for: 1. What is the overall pattern?: Do the data cluster together, or is there a gap such that one or more observations deviate from the rest? 2. Are there any suspected outliers? See Figure 3.3. 3. Do the data have a single mound or peak? If yes, then we have what is known as a unimodal distribution. Data with two βpeaksβ are referred to as bimodal, and data with many peaks are referred to as multimodal. See 1. 4. Is the distribution symmetric or skewed? See Figure 3.5. 50
Figure 3.3: Histogram with outliers Figure 3.4: Bimodal histogram Figure 3.5: Skewed histograms 51
Example 3.3 (Student Performance: Histograms).Now let us return to the student performance dataset. R code hist(stud_perf$G3, main="G3 histogram",xlab="G3 scores") G3 histogram G3 scores Frequency 0 5 10 15 20 0 20 40 60 80 Figure 3.6: R: Histogram of G3 scores Python code fig =stud_perf.G3.hist(grid=False) fig.set_title('G3 histogram') fig.set_xlabel('G3 scores'); 0.0 2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 G3 scores 0 20 40 60 80 100 G3 histogram Figure 3.7: Py: Histogram of G3 scores 52
ΔΉNote Do you notice any differences between the two histograms? In general, we now have a little more information to accompany the 5 number summaries. It appears that the distribution is not a basic unimodal one. There is a large spike of about 40 students who scored very low scores. As we mentioned earlier, it is not useful to inspect a histogram in a silo. Hence we shall condition on Motherβs education once more, to create separate histograms for each group. Remember that this is a case where the response variable G3 is quantitative, and the explanatory variable Medu is ordinal. R code library(lattice) histogram(~G3 |Medu, data=stud_perf, type="density", main="G3 scores, by Medu levels",as.table=TRUE) G3 scores, by Medu levels G3 Density 0.0 0.1 0.2 0.3 Medu 0 5 10 15 20 Medu Medu 0 5 10 15 20 Medu 0.0 0.1 0.2 0.3 Medu Figure 3.8: R: Lattice plot of G3 scores by Medu Python code stud_perf.G3.hist(by=stud_perf.Medu, figsize=(15,10), density=True, layout=(2,3)); 53
9 10 11 12 13 14 15 0.0 0.2 0.4 0.6 0.8 1.0 0 0 5 10 15 0.000 0.025 0.050 0.075 0.100 0.125 0.150 0.175 0.200 1 0 5 10 15 0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 2 0 5 10 15 0.00 0.02 0.04 0.06 0.08 0.10 0.12 0.14 3 0 5 10 15 20 0.00 0.02 0.04 0.06 0.08 0.10 0.12 4 Figure 3.9: Py: Lattice plot of G3 scores by Medu Although the heights of the panels in the two versions are not identical, we can, by looking at either one, see that the proportion of 0-scores reduces as the motherβs education increases. Perhaps this is reading too much into the dataset, but there seem to be more scores on the higher end for highest educated mothers. 3.3.2 Density Plots Histograms are not perfect - when using them, we have to experiment with the bin size since this could mask details about the data. It is also easy to get distracted by the blockiness of histograms. An alternative to histograms is the kernel density plot. Essentially, this is obtained by smoothing the heights of the rectangles in a histogram. Suppose we have observed an i.i.d sample π₯1,π₯2,β¦,π₯πfrom a continuous pdf π(β
). Then the kernel density estimate at π₯is given by ξ» π(π₯)= 1 πβ π β π=1πΎ(π₯βπ₯π β) where β’πΎis a density function. A typical choice is the standard normal. The kernel places greater weights on nearby points (to π₯). β’βis a bandwidth, which determines which of the nearest points are used. The effect is similar to the number of bins in a histogram. Example 3.4 (Student Performance: Density Estimates).Here is how we can make density plots with R and Python for the G3 scores. 54
R code densityplot(~G3, groups=Medu, data=stud_perf, auto.key = TRUE, main="G3 scores, by Medu",bw=1.5) G3 scores, by Medu G3 Density 0.00 0.05 0.10 0.15 β5 0 5 10 15 20 25 0 1 2 3 4 Figure 3.10: R: Estimated densities for G3 scores, by Medu Python code import matplotlib.pyplot as plt f, axs =plt.subplots(2,3, squeeze=False, figsize=(15,6)) out2 =stud_perf.groupby("Medu") for y,df0 in enumerate(out2): tmp =plt.subplot(2,3, y+1) df0[1].G3.plot(kind='kde') tmp.set_title(df0[0]) 6 8 10 12 14 16 18 0.04 0.06 0.08 0.10 Density 0 5 0 5 10 15 20 25 0.00 0.02 0.04 0.06 0.08 0.10 Density 1 10 0 10 20 30 0.00 0.02 0.04 0.06 0.08 0.10 Density 2 10 0 10 20 30 0.00 0.02 0.04 0.06 0.08 0.10 Density 3 10 0 10 20 30 0.00 0.02 0.04 0.06 0.08 Density 4 0.0 0.2 0.4 0.6 0.8 1.0 0.0 0.2 0.4 0.6 0.8 1.0 Figure 3.11: Py: Estimated densities for G3 scores, by Medu 55
As you can see, with density plots it is also possible to overlay them for closer comparison. This is not possible with histograms without some transparency in the rectangle colours. 3.3.3 Boxplots A boxplot provides a skeletal representation of a distribution. Boxplots are very well suited for comparing multiple groups. Here are the steps for drawing a boxplot: 1. Determine π1,π2and π3. The box is made from π1and π3. The median is drawn as a line or a dot within the box. 2. Determine the max-whisker reach: π3+1.5ΓπΌππ
; the min-whisker reach by π1β1.5Γ πΌππ
. 3. Any data point that is out of the range from the min to max whisker reach is classified as a potential outlier. 4. Excluding the potential outliers, the maximum point determines the upper whisker and the minimum point determines the lower whisker of a boxplot. A boxplot helps us to identify the median, lower and upper quantiles and outlier(s) (see Figure 3.12). Figure 3.12: Boxplot construction Example 3.5 (Student Performance: Boxplots).This time, instead of using motherβs education, we use the number of times a student goes out (goout) as the explanatory variable. From 56
the boxplot outputs, it appears there is no strong strictly increasing/decreasing trend associated with G3. Instead, although the differences between the categories are not large, it seems as though there is an βoptimalβ number of times that students could go out. Too little and too much going out leads to lower median G3 scores. R code bwplot(G3 ~goout, horizontal = FALSE,main="G3 scores, by goout", xlab="No. of times the student goes out per week", data=stud_perf) G3 scores, by goout No. of times the student goes out per week G3 0 5 10 15 20 12345 Figure 3.13: R: Boxplot of G3 scores, by gout variable Python code stud_perf.plot.box(column='G3', by='goout', xlabel='No. of times student goes out per week'); 57
Python code pd.plotting.scatter_matrix(concrete[['Cement','Slag','Comp_Strength','Water', 'SLUMP(cm)','FLOW(cm)']], figsize=(12,12)); 150 200 250 300 350 Cement 0 50 100 150 Slag 20 30 40 50 Comp_Strength 160 180 200 220 240 Water 0 10 20 SLUMP(cm) 200 300 Cement 20 40 60 FLOW(cm) 0 100 Slag 20 40 Comp_Strength 175 200 225 Water 0 20 SLUMP(cm) 25 50 75 FLOW(cm) Figure 3.22: Py: Scatterplot matrix for concrete dataset We can see that a few of the variables have several 0 values - cement, slag, slump and flow. Water appears to have some relation with slump and with flow. The scatterplots allow a visual understanding of the patterns, but it is usually also good to compute the correlation of all pairs of variables. 64
R code library(psych) corPlot(cor(concrete[, col_to_use]), cex=0.8,cex.axis=0.6, show.legend = FALSE) Correlation plot FLOW.cm. SLUMP.cm. Water Comp.Strength Slag Cement Cement Slag Comp.Strength Water SLUMP.cm. FLOW.cm. 0.19 β0.33 β0.12 0.63 0.91 1.00 0.15 β0.28 β0.22 0.47 1.00 0.91 0.22 β0.03 β0.25 1.00 0.47 0.63 0.45 β0.33 1.00 β0.25 β0.22 β0.12 β0.24 1.00 β0.33 β0.03 β0.28 β0.33 1.00 β0.24 0.45 0.22 0.15 0.19 Figure 3.23: R: Heatmap of correlation matrix for concrete data Python code The interactive heatmap created by Python is only available in the HTML format of the textbook. corr =concrete[['Cement','Slag','Comp_Strength','Water', 'SLUMP(cm)','FLOW(cm)']].corr() corr.style.background_gradient(cmap='coolwarm_r') 65
Table 3.5 Cement Slag Comp_Strength Water SLUMP(cm) FLOW(cm) Cement 1.000000 -0.243553 0.445725 0.221091 0.145913 0.186461 Slag -0.243553 1.000000 -0.331588 -0.026775 -0.284037 -0.327231 Comp_Strength 0.445725 -0.331588 1.000000 -0.254235 -0.223358 -0.124029 Water 0.221091 -0.026775 -0.254235 1.000000 0.466568 0.632026 SLUMP(cm) 0.145913 -0.284037 -0.223358 0.466568 1.000000 0.906135 FLOW(cm) 0.186461 -0.327231 -0.124029 0.632026 0.906135 1.000000 The plots you see above are known as heatmaps. They enable us to pick out groups of variables that are similar to one another. As you can see from the blue block in the lower right corner, Water,SLUMP.cm and FLOW.cm are very similar to one another. 3.6 References 3.6.1 Website References 1. UCI Machine Learning Repository: This site is an invaluable learning resource for data analysts. It contains several datasets for practice. In this chapter, we used the following two: β’Student Performance Dataset. β’Concrete Dataset 2. Kernel density estimation: Wikipedia contains a good overview explanation of the technique. 3.7 Exercises In the questions, do try to answer each question using both R and Python whenever possible. 1. From Figure 3.6 alone, can you make a rough guess: What proportion of students scored 6 or less? 2. Divide the concrete data into two subsets - one with Water less than or equal to 200 and one with Water greater than 200. Compute the Pearson correlations with compressive strength. How different are these values with the value for the full dataset? 3. Remove all rows with zero values for Slag from the concrete dataset. Create a QQ-plot for Slag and assess if the data is Normal. 4. How does bandwidth affect a density estimate (bw argument)? Experiment with different values to understand more. 5. Create numerical summaries of G3 scores, by goout, and compare the groups. 66
4 Exploring Categorical Data 4.1 Introduction A variable is known as a categorical variable if each observation belongs to one of a set of categories. Examples of categorical variables are: gender, religion, race and type of residence. Categorical variables are typically modeled using discrete random variables, which are strictly defined in terms whether or not the support is countable. The alternative to categorical variables are quantitative variables, which were introduced in the previous chapter. Another method for distinguishing between quantitative and categorical variables is to ask if there is a meaningful distance between any two points in the data. If such a distance is meaningful then we have quantitative data. For instance, it makes sense to compute the difference in systolic blood pressure between subjects, but it does not make sense to consider the mathematical operation (βsmokerβ - βnon-smokerβ). It is important to identify which type of data we have (quantitative or categorical), since it affects the exploration techniques that we can apply. There are two sub-types of categorical variables: β’ A categorical variable is ordinal if the observations can be ordered, but do not have specific quantitative values. β’ A categorical variable is nominal if the observations can be classified into categories, but the categories have no specific ordering. In this chapter, we shall discuss techniques for identifying the presence, and for measuring the strength, of the association between two categorical variables. We shall also demonstrate common visualisations used with categorical data. 4.2 Contingency Tables Example 4.1 (Chest Pain and Gender).Suppose that 1073 NUH patients who were at high risk for cardiovascular disease (CVD) were randomly sampled. They were then queried on two things: 1. Had they experienced the onset of severe chest pain in the preceding 6 months? (yes/no) 2. What was their gender? (male/female) The data would probably have been recorded in the following format (only first few rows shown): Patient Gender Pain 1 female no pain 2 male no pain 67
Patient Gender Pain 3 female no pain 4 male no pain 5 female no pain 6 male pain However, it would probably be summarised and presented in this format, which is known as a contingency table. pain no pain male 46 474 female 37 516 In a contingency table, each observation from the dataset falls in exactly one of the cells. The sum of all entries in the cells equals the number of independent observations in the dataset. All the techniques we shall touch upon in this chapter are applicable to contingency tables. 4.3 Visualisations 4.3.1 Bar charts A common method for visualising cross combinations of categorical data is to use a bar chart. Example 4.2 (Political Association and Gender Barchart).Consider data given in the table below where both variables are nominal. It cross-classifies poll respondents according to their gender and their political party aο¬iliation. Dem Ind Rep female 762 327 468 male 484 239 477 Here is R code to make a barchart for this data. library(lattice) x <- matrix(c(762,327,468,484,239,477), ncol=3,byrow=TRUE) dimnames(x) <- list(c("female","male"), c("Dem","Ind","Rep")) political_tab <- as.table(x) barchart(political_tab/rowSums(political_tab), main="Political association by gender", horizontal = FALSE,auto.key=TRUE) 68
Political association by gender Freq 0.0 0.2 0.4 0.6 0.8 1.0 female male Dem Ind Rep Figure 4.1: R: Stacked barchart for political association data We can see that the proportion of Republicans is higher for males than for females. The corresponding proportion of Democrats is lower. However, note that the barchart does not reflect that the marginal count for males was much less than that for females. Let us turn to making bar charts with pandas and Python. Example 4.3 (Claritin and Nervousness Barchart).Claritin is a drug for treating allergies. However, it has a side effect of inducing nervousness in patients. From a sample of 450 subjects, 188 of them were randomly assigned to take Claritin, and the remaining were assigned to take the placebo. The observed data was as follows: nervous not nervous claritin 4 184 placebo 2 260 A barchart can be created in Python with the following code. This barchart is slightly different from the one in Example 4.2 because it is not stacked. import numpy as np import pandas as pd claritin_tab =np.array([[4,184], [2,260]]) claritin_prop =claritin_tab/claritin_tab.sum(axis=1).reshape((2,1)) xx =pd.DataFrame(claritin_prop, columns=['nervous','not_nervous'], index=['claritin','placebo']) ax =xx.plot(kind='bar', stacked=False, rot=1.0, figsize=(10,4), title='Nervousness by drug') ax.legend(loc='upper left'); 69
claritin placebo 0.0 0.2 0.4 0.6 0.8 1.0 Nervousness by drug nervous not_nervous Figure 4.2: Py: Barchart for Claritin data The proportion of patients who are not nervous is similar in both groups. 4.3.2 Mosaic plots Unlike a bar chart, a mosaic plot reflects the count in each cell (through the area), along with the proportions of interest. Let us inspect how we can make mosaic plots for the political association data earlier. Example 4.4 (Political Association and Gender Mosaic Plot).The colours in Figure 4.3 reflect the sizes of the standardised residuals. We shall discuss this in more detail in Section 4.4.3. The greater width of the tiles in the column for females reflects the larger marginal count for females. Compare this visualisation with Figure 4.1. R code mosaicplot(political_tab, shade=TRUE,main="Political association by gender") 70
Standardized Residuals: <β4β4:β2β2:0 0:2 2:4 >4 Political association by gender female male DemInd Rep Figure 4.3: R: Mosaic plot for political association data Python code from statsmodels.graphics.mosaicplot import mosaic import matplotlib.pyplot as plt political_tab =np.asarray([[762,327,468], [484,239,477]]) mosaic(political_tab, statistic=True, gap=0.05); 71
0 1 0 1 2 0 0 0 1 0 2 1 0 1 1 1 2 Figure 4.4: Py: Mosaic plot for political association data 4.3.3 Conditional Density Plots When we have one categorical and one quantitative variable, the kind of plot we make really depends on which is the response, and which is the explanatory variable. If the response variable is the quantitative one, it makes sense to create boxplots or histograms. However, if the response variable is a the categorical one, we should really be making something along these lines: Example 4.5 (Heart Failure Dataset).The dataset at UCI repository contains records on 299 patients who had heart failure. The data was collected during the follow-up period; each patient had 13 clinical features recorded. The primary variable of interest was whether they died or not. Suppose we wished to plot how this varied with age (a quantitative variable): data_path <- file.path("data","heart+failure+clinical+records", "heart_failure_clinical_records_dataset.csv") heart_failure <- read.csv(data_path) spineplot(as.factor(DEATH_EVENT) ~age, data=heart_failure, ylab = "Death",xlab="Age",main="Proportion dying, by age") 72
Proportion dying, by age Age Death 40 45 50 55 60 65 70 80 1 0 0.0 0.4 0.8 Figure 4.5: R: Spine plot for heart failure data It reflects how the probability of an event varies with the quantitative explanatory variable. A smoothed version of this is known as the conditional density plot: cdplot(as.factor(DEATH_EVENT) ~age, data=heart_failure, ylab = "Death",xlab="Age",main="Proportion dying, by age") Proportion dying, by age Age Death 50 60 70 80 90 1 0 0.0 0.4 0.8 Figure 4.6: R: Conditional density plot for heart failure data From both Figure 4.5 and Figure 4.6, it is clear to see that there is an increased proportion of death during follow-up associated with older patients. 4.4 Tests for Independence In the contingency table above, the two categorical variables are Gender and Presence/Absence of Pain. With contingency tables, the main inferential task usually relates to assessing the association between the two categorical variables. 73
4.5 Measures of Association This sections covers bivariate measures of association for categorical variables. 4.5.1 Odds Ratio The most generally applicable measure of association, for 2x2 tables, is the Odds Ratio (OR). Suppose we have πand πto be Bernoulli random variables with (population) success probabilities π1and π2. We define the odds of success for πto be π1 1βπ1 Similarly, the odds of success for random variable πis π2 1βπ2. In order to measure the strength of their association, we use the odds ratio: π1/(1βπ1) π2/(1βπ2) The odds ratio can take on any value from 0 to β. β’ A value of 1 indicates no association between πand π. If πand πwere independent, this is precisely what we would observe. β’ Deviations from 1 indicate stronger association between the variables. β’ Note that, for odds ratios, deviations from 1 are not symmetric. For a given pair of variables, an association of 0.25 or 4 is the same - it is just a matter of which variable we put in the numerator odds. Due to the above asymmetry, we often use the log-odds-ratio instead: log π1/(1βπ1) π2/(1βπ2) β’ Log-odds-ratios can take values from ββto β. β’ A value of 0 indicates no association between πand π. β’ Deviations from 0 indicate stronger association between the variables, and deviations are now symmetric; a log-odds-ratio of -0.2 indicates the same strength as 0.2, just the opposite direction. To obtain a confidence interval for the odds-ratio, we work with the log-odds ratio and then exponentiate the resulting interval. Here are the steps for a 2Γ2table: 1. Suppose we label the observed counts in the table as π11,π12,π21,π22. 2. The sample odds ratio is ξΌ ππ
=π11Γπ22 π12Γπ21 3. For a large sample size, it can be shown that log ξΌ ππ
follows a Normal distribution. Hence a 95% confidence interval can be obtained through log π11Γπ22 π12Γπ21 Β±π§0.025Γπ΄ππΈ(log ξΌ ππ
) 80
where the ASE (Asymptotic Standard Error) of the estimator is β1 π11 +1 π12 +1 π21 +1 π22 Example 4.10 (Chest Pain and Gender Odds Ratio).Let us compute the confidence interval for the odds ratio in the chest pain and gender example from earlier. R code library(DescTools) OddsRatio(chest_tab,conf.level = .95) odds ratio lwr.ci upr.ci 1.3534040 0.8626023 2.1234612 Python code import statsmodels.api as sm chest_tab2 =sm.stats.Table2x2(chest_array) print(chest_tab2.summary()) Estimate SE LCB UCB p-value -------------------------------------------------- Odds ratio 1.353 0.863 2.123 0.188 Log odds ratio 0.303 0.230 -0.148 0.753 0.188 Risk ratio 1.322 0.872 2.004 0.188 Log risk ratio 0.279 0.212 -0.137 0.695 0.188 -------------------------------------------------- 4.5.2 For Ordinal Variables When both variables are ordinal, it is often useful to compute the strength (or lack) of any monotone trend association. It allows us to assess if As the level of πincreases, responses on πtend to increase toward higher levels, or responses on πtend to decrease towards lower levels. For instance, perhaps job satisfaction tends to increase as income does. In this section, we shall discuss a measure for ordinal variables, analogous to Pearsonβs correlation for quantitative variables, that describes the degree to which the relationship is monotone. It is based on the idea of a concordant or discordant pair of subjects. Definition 4.1. 81
β’ A pair of subjects is concordant if the subject ranked higher on πalso ranks higher on π. β’ A pair is discordant if the subject ranking higher on πranks lower on π. β’ A pair is tied if the subjects have the same classification on πand/or π. If we let β’πΆ: number of concordant pairs in a dataset, and β’π·: number of discordant pairs in a dataset. Then if πΆis much larger than π·, we would have reason to believe that there is a strong positive association between the two variables. Here are two measures of association based on πΆand π·: 1. Goodman-Kruskal πΎis computed as πΎ=πΆβπ· πΆ+π· 2. Kendall ππis ππ=πΆβπ· π΄ where π΄is a normalising constant that results in a measure that works better with ties, and is less sensitive than πΎto the cut-points defining the categories. However, πΎhas the advantage that it is more easily interpretable. For both measures, values close to 0 indicate a very weak trend, while values close to 1 (or -1) indicate a strong positive (negative) association. Example 4.11 (Job Satisfaction by Income).Consider the following table, obtained from Agresti (2012). The original data come from a nationwide survey conducted in the US in 1996. R code x <- matrix(c(1,3,10,6, 2,3,10,7, 1,6,14,12, 0,1,9,11), ncol=4,byrow=TRUE) dimnames(x) <- list(c("<15,000","15,000-25,000","25,000-40,000",">40,000"), c("Very Dissat.","Little Dissat.","Mod. Sat.", "Very Sat.")) us_svy_tab <- as.table(x) output <- Desc(x, plotit = FALSE,verbose = 3) output[[1]]$assocs estimate lwr.ci upr.ci Contingency Coeff. 0.2419 - - Cramer V 0.1439 0.0000 0.1693 Kendall Tau-b 0.1524 -0.0083 0.3130 Goodman Kruskal Gamma 0.2211 -0.0085 0.4507 82
Stuart Tau-c 0.1395 -0.0082 0.2871 Somers D C|R 0.1417 -0.0080 0.2915 Somers D R|C 0.1638 -0.0116 0.3392 Pearson Correlation 0.1772 -0.0241 0.3647 Spearman Correlation 0.1769 -0.0245 0.3645 Lambda C|R 0.0377 0.0000 0.2000 Lambda R|C 0.0159 0.0000 0.0693 Lambda sym 0.0259 0.0000 0.1056 Uncertainty Coeff. C|R 0.0311 -0.0076 0.0699 Uncertainty Coeff. R|C 0.0258 -0.0069 0.0585 Uncertainty Coeff. sym 0.0282 -0.0072 0.0637 Mutual Information 0.0508 - - Python code from scipy import stats us_svy_tab =np.array([[1,3,10,6], [2,3,10,7], [1,6,14,12], [0,1,9,11]]) dim1 =us_svy_tab.shape x=[];y=[] for iin range(0, dim1[0]): for jin range(0, dim1[1]): for kin range(0, us_svy_tab[i,j]): x.append(i) y.append(j) kt_output =stats.kendalltau(x, y) print(f"The estimate of tau-b is {kt_output.statistic:.4f}.") The estimate of tau-b is 0.1524. The output shows that both πΎ=0.22and ππ=0.15are close to significant. The lower confidence limit is close to being positive. 4.6 Further readings In general, I have found that R packages seem to have a lot more measures of association for categorical variables. In Python, the measures are spread out across packages. Above, we have only scratched the surface of what is available. If you are keen, do read up on 1. Somerβs D (for association between nominal and ordinal) 2. Mutual Information (for association between all types of pairs of categorical variables) 83
3. Polychoric correlation (for association between two ordinal variables) Also, take note of how log odds ratios, ππand πΎwork. Firstly, values close to 0 reflect weak association. Values of πand βπindicate the same strength, but different direction of association. This allows the same intuition that Pearsonβs correlation does. When you are presented with new metrics, try to understand them by asking similar questions about them. 4.7 References 4.7.1 Website References 1. Documentation pages from statsmodels: β’Mosaic plots β’Contingency tables 2. Documentation pages from scipy: β’Fisher test with scipy β’π2-test 3. Heart failure data 4. More information on Kendall ππstatistic 5. The π2test we studied is a test of independence. It is a variant of the π2goodness-of-fit test, which is used to assess if data come from a particular distribution. In our case, the presumed distribution is one where the variables are independent. Read more about the goodness-of-fit test here. 4.8 Exercises 1. Use Python to create the spineplot for the heart failure data. 2. Write a function in Python that converts a contingency table into βlongβ format. 3. What is the interpretation of πΎimplied by the text? 4. From the political association data, extract the standardised residuals (under independence), and create a QQ-plot. 5. Apply the Fisher Exact test to the political association data. How does it work in this case? 84
5 Robust Statistics 5.1 Introduction Introductory statistics courses describe and discuss inferential methods based on the assumption that data is Normally distributed. However, we never truly know the distribution from which our data has arisen. The sample itself may deviate from Normality in various ways. To begin with, we might observe that the data has heavier tails than a Normal distribution. Second, the data could suggest that the originating distribution is heavily skewed, unlike the symmetric Normal. A third way in which the Normal-based method could breakdown is when our dataset has extreme values, referred to as outliers. In such cases, many investigators will drop the anomalous points and proceed with the analysis on the remaining observations. This is not ideal for the following reasons: 1. The sharp decision to reject an observation is wasteful. We can do better by downweighting the dubious observations. 2. It can be diο¬icult to spot or detect outliers in multivariate data. Continuing to use Normal based methods will result in confidence intervals and hypothesis tests that have low power. Instead, statisticians have developed a suite of methods that are robust to the assumption of Normality. These techniques may be sub-optimal when the data is truly Normal, but they quickly outperform the Normal-based method as soon as the distribution starts to deviate from Normality. In this chapter, we shall introduce the concept of robustness and estimators of location and scale that have this property. Although we only touch on basic statistics in this topic, take note that robust techniques exist for regression and ANOVA as well. It is a vastly under-used technique. 5.2 Notation For the rest of this topic, let us settle on some notation. Suppose we have an i.i.d sample ππ from a continuous pdf π, where π=1,β¦,π. β’ We use ππ,π to refer to the π-th quantile of π, i.e. π(πβ€ππ,π)=π β’ For standard Normal quantiles, we use π§π. Ξ¦(π§π)=π(πβ€π§π)=π β’ We denote the order statistics from the sample with π(π). In other words, π(1) β€π(2) β€β―β€π(π) We denote the sample median as π(1/2). 85
5.3 Datasets For this topic, we shall work with a couple of datasets that are clearly not Normal. Example 5.1 (Copper in Wholemeal Flour).The dataset chem comes from the package MASS. The data was recorded as part of an analytical chemistry experiment β the amount of copper (ππ) in wholemeal flour was measured for 24 samples. library(MASS) hist(chem, breaks = 20,xlab="Amount of copper") Histogram of chem Amount of copper Frequency 5 10 15 20 25 30 0 4 8 12 Figure 5.1: Copper measurements dataset sort(chem) [1] 2.20 2.20 2.40 2.40 2.50 2.70 2.80 2.90 3.03 3.03 3.10 3.37 [13] 3.40 3.40 3.40 3.50 3.60 3.70 3.70 3.70 3.70 3.77 5.28 28.95 mean(chem) [1] 4.280417 Although 22 out of the 24 points are less than 4, the mean is 4.28. This statistic is clearly being affected by the largest two values. This topic is about techniques that will work well even in the presence of such large anomalous values. The second dataset is from a textbook on robust estimation techniques. 86
Example 5.2 (Self-awareness Dataset).For a second dataset, we use one on self-awareness from (Wilcox and R 2011), where participants in a psychometric study were timed how long they could keep a portion of an apparatus in contact with a specified target. awareness <- c(77,87,88,114,151,210,219,246,253,262,296,299,306, 376,428,515,666,1310,2611) hist(awareness, breaks=10,xlab="Timing") Histogram of awareness Timing Frequency 0 500 1000 1500 2000 2500 02468 Figure 5.2: Self-awareness study timing mean(awareness) [1] 448.1053 Just like the data in Example 5.1, this data too is highly skewed to the right. The mean of the full dataset is larger than the 3rd quartile! 5.4 Assessing Robustness The focus of this course is on the computational aspects of performing data analyses. However, this section and the next are a little theoretical. They only exist to provide a better overview of robust statistical techniques. Section 5.4.1 introduces an approach for comparing two estimators in general. The remaining subsections (Section 5.5 onwards) briefly list ways in which robust statistics are evaluated. 87
5.4.1 Asymptotic Relative Eο¬iciency Suppose we wish to estimate a parameter πof a distribution using a sample of size π. We have two candidate estimators ξ» πand ξ» π. Definition 5.1 (Asymptotic Relative Eο¬iciency (ARE)).The asymptotic relative eο¬iciency of ξ» πrelative to ξ» πis π΄π
πΈ( ξ» π; ξ» π)= lim πββvariance of ξ» π variance of ξ» π Usually, ξ» πis the optimal estimator according to some criteria. The intuitive interpretation is that when using ξ» π, we only need π΄π
πΈtimes as many observations as when using ξ» π. Smaller values of ARE indicate that ξ» πis better than ξ» π. Here are a couple of commonly used estimators and their AREs. Example 5.3 (Median versus Mean).If our data is known to originate from a Normal distribution, due to its symmetry, we can use either the sample median or the sample mean to estimate π. Let ξ» π= ξ³½ πand ξ» π=π(1/2). Then it can be shown that π΄π
πΈ( ξ» π; ξ» π)=2/πβ64% The sample median is less eο¬icient than the sample mean, when the true distribution is Normal. Here is an example of when robust statistics prove to be superior to non-robust ones. Example 5.4 (Contaminated Normal Variance Estimate).Suppose first that we have πobservations ππβΌπ(π,π2), and we wish to estimate π2. Consider the two estimators: 1. ξ»π2=π 2=1 πβ1βπ π=1(ππβξ³½ π)2 2. ξ» π2=π2π/2, where π=1 πβ π|ππβξ³½ π| In this case, when the underlying distribution truly is Normal, we have that π΄π
πΈ( ξ» π2; ξ»π2)=87.6% However, now consider a situation where ππβΌ π(π,π2)with probability 1βπand ππβΌ π(π,9π2)with probability π. Let us refer to this as a contaminated Normal distribution. As you can see from Figure 5.3, the two pdfs are almost indistinguishable by eye. However, the ARE values are very different: πARE 0 87.6% 0.01 144% 88
πARE The usual π 2loses optimality very quickly; we can obtain more precise estimates using ξ» π2. This example was taken from section 5.5 of Venables and Ripley (2013). There are three main approaches of assessing the robustness of an estimator. Let us cover the intuitive ideas here. In this section, πΉrefers to the cdf from which the sample was obtained. 5.5 Requirements of Robust Summaries 1. Qualitative Robustness: The first requirement of a robust statistic is that it if the underlying distribution πΉchanges slightly, then the estimate should not change too much. 2. Infinitesimal Robustness: The second requirement is tied to the concept of the influence function of an estimator. Roughly speaking, the influence function measures the relative extent that a small perturbation in πΉhas on the value of the estimate. In other words, it reflects the influence of adding one more observation to a large sample. 3. Quantitative Robustness: The final requirement is related to the contaminated distribution we touched on in Example 5.4. Consider πΉπ₯,π =(1βπ)πΉ+πΞπ₯ where Ξπ₯is the degenerate probability distribution at π₯. The minimum value of πfor which the estimator goes to infinity as π₯gets large, is referred to as the breakdown point. For the sample mean, the breakdown point is π=0. For the sample median, the breakdown point is π=0.5. 5.6 Measures of Location The location parameter of a distribution is a value that characterises βa typicalβ observation, or the middle of the distribution. It is not always the mean of the distribution, but in the case of a symmetric distribution it will be. 5.6.1 M-estimators Before we introduce robust estimators for the location, let us revisit the most commonly used one - the sample mean. Suppose we have observed π₯1,π₯2,β¦,π₯π, a random sample from a π(π,π2)distribution. As a reminder, here is how we derive the MLE for π. The likelihood function is πΏ(π,π2)= π β π=1 1 β2ππ2πβ(π₯πβπ)2/(2π2) The log-likelihood is log πΏ=π(π,π2)=βπlog πβπ 2log(2π)β 1 2π2π β π=1(π₯πβπ)2(5.1) 89
5.10 References 5.10.1 Website References 1. Wikipedia on Robust Statistics This page contains visualisations of the πcurves for the estimators mentioned above, along with others. 2. Scipy stats: This page contains information on the median_abs_deviation(), trim_mean(), and mstats.winsorize() methods in Python. 5.11 Exercises 1. List two ways in which data could possibly deviate from Normality. 2. Compute the trimmed mean for the G3 variable in the student performance dataset, using πΎ=0.1. 3. Winsorise the chem dataset, with πΎ=0.1, and create QQ-plots for the original and new dataset. 4. Identify the error(s) in the following R implementation of MAD, and create a Python function with the correct algorithm. mad2 <- function(x) { deviations <- abs(x -mean(x)) median(deviations) } 5. Giniβs mean difference is defined to be the mean absolute difference between any two distinct elements of a vector. Write a function that implements it, and compare it with robust measures of spread that were discussed in this chapter. 96
6 Introduction to SAS 6.1 Introduction SAS (Statistical Analysis System) is a software that was originally created in the 1960s. Today, it is widely used by statisticians working in biostatistics and the pharmaceutical industries. Unlike Python and R, it is a proprietary software. The full license is quite expensive for a low-usage case such as ours. Thankfully, there is a free web-based version that we can use for our course. 6.2 Registering for a SAS Studio Account The first step is to create a SAS profile: Use your NUS email address to register and create your SAS profile using this link. Once you have verified your account using the email that would be sent to you, the following link should take you to the login page shown in Figure 6.1. Figure 6.1: SAS: Login page Subsequently logging in should take you to the landing page, where you can begin writing SAS code and using SAS. This interface can be seen in Figure 6.2. 97
Figure 6.2: SAS: Studio interface 6.3 An Overview of SAS Language The SAS language is not a fully-fledged programming language like Python is, or even R. For the most part, we are going to capitalise on the point-and-click interface of SAS Studio in our course. However, even so, it is good to understand a little about the language so that we can modify the options for different procedures as necessary. A SAS program is a sequence of statements executed in order. Keep in mind that: Every SAS statement ends with a semicolon. SAS programs are constructed from two basic building blocks: DATA steps and PROC steps. A typical program starts with a DATA step to create a SAS data set and then passes the data to a PROC step for processing. Example 6.1 (Creating and Printing a Dataset).Here is a simple program that converts miles to kilometres in a DATA step and then prints the results with a PROC step: DATA distance; Miles = 26.22; Kilometer = 1.61 *Miles; PROC PRINT DATA=distance; RUN; To run the above program, click on the βRunning Manβ icon in SAS studio. You should obtain the output shown in Figure 6.3. This dataset has only one observation (row). Data steps start with the DATA keyword. This is followed by the name for the dataset. Procedures start with PROC followed by the name of the particular procedure (e.g. PRINT, SORT or PLOT) you wish to run on the dataset. Most SAS procedures have only a handful of possible statements. A step ends when SAS encounters a new step (marked by a DATA or PROC statement) or a RUN statement. RUN statements are not part of a DATA or PROC step; they are global statements. 98
Figure 6.3: SAS: Simple data creation Example 6.2 (Creating a Dataset Inline).The following program explicitly creates a dataset within the DATA step. /*CREATING DATA MANUALLY:;*/ DATA ex_1; INPUT subject gender $CA1 CA2 HW $; DATALINES; 10 m80 84 a 7m85 89 a 4f90 86 b 20 m82 85 b 25 f94 94 a 14 f88 84 c ; PROC MEANS DATA=ex_1; VAR CA1 CA2; RUN; The output for the above code is shown in Figure 6.4 and Figure 6.5. In the statements above, the $βs in the INPUT statement inform SAS that the preceding variables (gender and HW) are character. Note how the semi-colon for the DATALINES appears after all the data has been listed. PROC MEANS creates basic summary statistics for the variables listed. To review, there are only 2 types of steps in SAS programs: 6.4 Basic Rules for SAS Programs 6.4.1 For SAS statements β’ All SAS statements (except those containing data) must end with a semicolon (;). β’ SAS statements typically begin with a SAS keyword. (DATA, PROC). β’ SAS statements are not case sensitive, that is, they can be entered in lowercase, uppercase, or a mixture of the two. βExample : SAS keywords (DATA, PROC) are not case sensitive 99
Figure 6.4: SAS: Inline data created Figure 6.5: SAs: PROC MEANS output DATA steps β’ begin with DATA statements. β’ read and modify data. β’ create a SAS dataset. PROC steps β’ begin with PROC statements. β’ perform specific analysis or function. β’ produce reports or results. β’ A delimited comment begins with a forward slash-asterisk (/) and ends with an asteriskforward slash (/). All text within the delimiters is ignored by SAS. 6.4.2 For SAS names β’ All names must contain between 1 and 32 characters. β’ The first character appearing in a name must be a letter (A, B, β¦ Z, a, b, β¦, z) or an underscore ( ). Subsequent characters must be letters, numbers, or underscores. That is, no other characters, such as $, %, or & are permitted. β’ Blanks also cannot appear in SAS names. β’ SAS names are not case sensitive, that is, they can be entered in lowercase, uppercase, or a mixture of the two. (SAS is only case sensitive within quotation marks.) 6.4.3 For SAS variables β’ If the variable in the INPUT statement is followed by a dollar sign ($), SAS assumes this is a character variable. Otherwise, the variable is considered as a numeric variable. 6.5 Reading Data into SAS In this topic, we shall introduce a new dataset, also from the UCI Machine Learning repository. 100
Example 6.3 (Bike Rentals).The dataset was collected by the authors in Fanaee-T and Gama (2013). It contains information on bike-sharing rentals in Washington D.C. USA for the years 2011 and 2012, along with measurements of weather. The original dataset contained hourly and daily aggregated data. For our class, we use a re-coded version of the daily data. Our dataset can be found on Canvas as bike2.csv. Here is the data dictionary: Field Description instant Record index dteday Date season spring, summer, fall, winter) yr Year (0: 2011, 1: 2012) mnth Abbreviated month holiday Whether the day is a holiday or not weekday Abbreviated day of the week workingday yes: If day is neither weekend nor holiday is 1, no: Otherwise weathersit Weather situation: clear: Clear, Few clouds, Partly cloudy, Partly cloudy; mist: Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist; light_precip: Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered clouds; heavy_precip: Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog temp Normalized temperature in Celsius. Divided by 41 (max) atemp Normalized perceived temperature in Celsius. Divided by 50 (max) hum Normalized humidity. Divided by 100 (max) windspeed Normalized wind speed. Divided by 67 (max) casual Count of casual rental bike users registered Count of registered rental bike users cnt Count of total rental bikes including both casual and registered Our first step will be to load the dataset into SAS Studio. 6.6 Uploading and Using Datasets To use our own datasets on SAS Studio, we have to execute the following steps: 1. Create a new library. In SAS, a library is a collection of datasets. If you already have a library created, you can simply import datasets into it. The default library on SAS is called WORK. However, the datasets in WORK will be purged every time you sign out. Hence it is better to create a new, dedicated library for this course. 2. Import your dataset (csv, xlsx, etc.) into the library. 3. After this, the data will be available for use with the reference name <library-name>.<dataset-name>. From the βLibrariesβ menu on the left of SAS studio, click on the βNew libraryβ icon (the one circled in red in Figure 6.6), and create a new library called βST2137β. You can use the default suggested path for the library. Now expand the menu for βServer Files and Foldersβ and upload bike2.csv file to SAS, using the circled icon in Figure 6.7. 101
Figure 6.6: SAS: New library creation icon Figure 6.7: SAS: Upload data icon 102
Finally, right-click on the top of the main Studio area (where we write code) and select βNew Import Dataβ. Select the bike2.csv that has just been uploaded, and modify the OUTPUT DATA settings to Library ST2137 and Data set name BIKE2. Click on the running man, and your dataset is now ready for use in SAS studio! 6.7 Summarising Numerical Data Most of the SAS routines we are going to work with can be found in the βTasks and Utilitiesβ section (see highlighted tasks in Figure 6.8). Figure 6.8: SAS: Common ST2137 procedures 6.7.1 Numerical Summaries Example 6.4 (5-number Summaries).We expect that the total count of users will vary by the seasons. Hence, we begin by computing five-number summaries for each season. Under Tasks, go to Statistcs > Summary Statistics. Select cnt as the analysis variable, and season as the classification variable. Under the options tab, select the lower and upper quartiles, along with comparative boxplots. The output should look like Figure 6.9: We observe that the median count is highest for fall, followed by summer, winter and lastly spring. The spreads, as measured by IQR, are similar across the seasons: approximately 2000 users. In the middle 50%, the count distribution for spring is the most right-skewed. 6.7.2 Scatter Plots Example 6.5 (Casual vs Registered Scatterplot).To create a scatterplot in SAS, go to Tasks > Graphs > Scatter Plot. 103
Figure 6.9: SAS: 5-number-summaries and boxplots for bike rental data Specify casual on the x-axis, registered on the y-axis, and workingday as the Group. You should observe the plot created Figure 6.10: Figure 6.10: SAS: Scatterplot for bike rental data We can see that there seem to be two different relationships between the counts of casual and registered users. The two relationships correspond to whether it as a working day or not. 6.7.3 Histograms Example 6.6 (Casual Users Distribution).Now suppose we focus on casual users, and study the distribution of counts by whether a day is a working day or not. To create a histogram, 104
go to Tasks > Graph > Histogram. Select casual as the analysis variable, and workingday as the group variable. Figure 6.11: SAS: Histograms for bike rental data From Figure 6.11, we can see that the distribution is right-skewed in both cases. However, the range of counts for non-working days extends further, to about 3500. 6.7.4 Boxplots Example 6.7 (Boxplots for Casual Users, by Season).In Example 6.4, we observed that total counts vary by season, and in Example 6.6, we observed that working days seem to have fewer casual users. Let us investigate if this difference is related to season. To create boxplots, go to Tasks > Box Plot. Select casual as the analysis variable, season as the category and workingday as the subcategory. You should obtain the plot in Figure 6.12. To order the seasons according to the calendar, I had to add this line to the code: proc sgplot data=ST2137.BIKE2; vbox casual /category=season group=workingday grouporder=ascending; xaxis values=('spring' 'summer' 'fall' 'winter'); yaxis grid; run; There is little further insight compared to the previous two examples. However, now try the same plots, but on the log scale (modify the APPEARANCE tab and re-run). You should now obtain Figure 6.13. Now, we can observe that the difference within each season is constant across seasons. Because the difference in logarithms is constant, it means that, on the original scale, it is a constant multiplicative factor that increases counts from workingday to non-working day. We have arrived at a more succint representation of the relationship by using the log transform. 105
7.2.5 Step 5: State your conclusion This is the binary decision stage. If the π-value is less than the stated significance level, we conclude that we reject π»0. Otherwise, we say that we do not reject π»0. It is conventional to use this terminology (instead of saying βaccept π»1β) since our π-value is obtained with respect to π»0. 7.3 Confidence Intervals Confidence intervals are an alternative method of inference for population parameters. Instead of yielding a binary reject/do-not-reject result, they return a confidence interval that contains the plausible values for the population parameter. Many confidence intervals are derived by inverting hypothesis tests, and almost all confidence intervals are of the form Sample estimate Β±margin of error For instance, if we observe π₯1,β¦,π₯πfrom a Normal distribution, and wish to estimate the mean of the distribution, the 95% confidence interval based on the the π‘distribution is ξ³½π₯Β±π‘0.025,πβ1Γπ βπ where β’π is the sample standard deviation, and β’π‘0.025,πβ1 is the 0.025-quantile from the π‘distribution with πβ1degrees of freedom. The formulas for many confidence intervals rely on asymptotic Normality of the estimator. However, this is an assumption that can be overcome with the technique of bootstrapping. We shall touch on this in the final topic of our course, in Section 10.6.2. Bootstrapping can also be used to sidestep the distributional assumptions in hypothesis tests, but I still much prefer confidence intervals to tests because they yield an interval; they provide much more information than a binary outcome. 7.4 Parametric Tests Parametric tests are hypothesis tests that assume some form of distribution for the sample (or population) to follow. An example of such a test is the π‘-test, which assumes that the data originate from a Normal distribution. Conversely, nonparametric tests are hypothesis tests that do not assume any form of distribution for the sample. It seems we should always use non-parametric tests since distributional assumptions would not be violated, right? Unfortunately, since nonparametric tests are so general, they do not have a high discriminative ability - we say that they have low power. In other words, if a dataset truly comes from a Normal distribution, using the π‘-test would be able to detect smaller differences between the groups better than a non-parametric test. In this section, we cover parametric tests for comparing the difference in mean between two groups. 112
7.4.1 Independent Samples Test In an independent samples π‘-test, observations in one group yield no information about the observations in the other group. Independent samples can arise in a few ways: β’ In an experimental study, study units could be assigned randomly to different treatments, thus forming the two groups. β’ In an observational study, we could draw a random sample from the population, and then record an explanatory categorical variable on each unit, such as the gender or seniorcitizen status. β’ In an observational study, we could draw a random sample from a group (say smokers), and then a random sample from another group (say non-smokers). This would result in a situation where the independent 2-sample π‘-test is appropriate. Formal Set-up Formally speaking, this is how the independent 2-sample t-test works: Suppose that π1,π2,β¦,ππ1are independent observations from group 1, and π1,β¦ππ2are independent observations from group 2. It is assumed that ππβΌ π(π1,π2),π=1,β¦,π1(7.1) ππβΌ π(π2,π2),π=1,β¦,π2(7.2) The null and alternative hypotheses would be π»0βΆ π1=π2 π»1βΆ π1β π2 The test statistic for this test is: π1=(ξ³½ πβ ξ³½ π)β0 π πβ1/π1+1/π2 where π 2 π=(π1β1)π 2 1+(π2β1)π 2 2 π1+π2β2 Under π»0, the test statistic π1βΌπ‘π1+π2β2. When we use a software to apply the test above, it will typically also return a confidence interval, computed as (ξ³½ πβ ξ³½ π)Β±π‘π1+π2β2,1βπΌ/2Γπ πβ1/π1+1/π2 The set-up above corresponds to the case where the variance within each group is assumed to be the same. We use information from both groups to estimate the common variance. If we 113
find evidence in the data to the contrary, we used the unpooled variance in the denominator of π1: π1,π’πππππππ =(ξ³½ πβ ξ³½ π)β0 βπ 2 1/π1+π 2 2/π2 where π 2 1and π 2 2are the sample variance from groups 1 and 2. The test statistic still follows a π‘distribution, but the degrees of freedom are approximated. This approximation is known as the Satterthwaite approximation. Example 7.1 (Abalone Measurements).The dataset on abalone measurements from the UCI machine learning repository contains measurements of physical characteristics, along with the gender status. We derive a sample of 50 measurements of male and female abalone records for use here. Our goal is to study if there is a significant difference between the viscera weight1 between males and females. The derived dataset can be found on Canvas. R code abl <- read.csv("data/abalone_sub.csv") x <- abl$viscera[abl$gender == "M"] y <- abl$viscera[abl$gender == "F"] t.test(x, y, var.equal=TRUE) Two Sample t-test data: x and y t = 0.91008, df = 98, p-value = 0.365 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -0.02336287 0.06294287 sample estimates: mean of x mean of y 0.30220 0.28241 Python code import pandas as pd import numpy as np from scipy import stats import statsmodels.api as sm abl =pd.read_csv("data/abalone_sub.csv") #abl.head() 1Viscera is the gut weight after bleeding out the abalone (in grams). 114
#abalone_df.describe() x=abl.viscera[abl.gender == "M"] y=abl.viscera[abl.gender == "F"] t_out =stats.ttest_ind(x, y) ci_95 =t_out.confidence_interval() print(f""" * The p-value for the test is {t_out.pvalue:.3f}. * The actual value of the test statistic is {t_out.statistic:.3f}. * The upper and lower limits of the CI are ({ci_95[0]:.3f},{ci_95[1]:.3f}). """) * The p-value for the test is 0.365. * The actual value of the test statistic is 0.910. * The upper and lower limits of the CI are (-0.023, 0.063). SAS Output When we run the independent samples t-test on SAS, we should observe the output in Figure 7.1. Figure 7.1: SAS: Independent samples t-test, Abalone data The assumptions of the test include Normality and equal variance. Let us assess the equality of variance first. While there are many hypothesis tests specifically for assessing if variances 115
are equal (e.g. Levene, Bartlett), in our class, I advocate a simple rule of thumb. If the larger s.d is more than twice the smaller one, than we should not use the equal variance form of the test. This rule of thumb is widely used in practice (see Section 7.7.1). R code aggregate(viscera ~gender, data=abl, sd) gender viscera 1 F 0.1087070 2 M 0.1087461 Python code abl.groupby('gender').describe() viscera count mean std min 25% 50% 75% max gender F 50.0 0.28241 0.108707 0.095 0.201250 0.275 0.365125 0.575 M 50.0 0.30220 0.108746 0.040 0.253125 0.310 0.348750 0.638 To assess the Normality assumption, we make also histograms and qq-plots (see Figure 7.2, Figure 7.3, and Figure 7.4). ΔΉNote Only the R code is shown here. library(lattice) histogram(~viscera |gender, data=abl, type="count") qqnorm(y, main="Female Abalones"); qqline(y) qqnorm(x, main="Male Abalones"); qqline(x) We would conclude that there is no significant difference between the mean viscera weight of males and females. Apart from qq-plots, it is worthwhile to touch on additional methods that are used to assess how much a dataset deviates from Normality. 116
viscera Count 0 5 10 15 0.0 0.2 0.4 0.6 F 0.0 0.2 0.4 0.6 M Figure 7.2: R: Histograms for males and females β2 β1 0 1 2 0.1 0.3 0.5 Female Abalones Theoretical Quantiles Sample Quantiles Figure 7.3: R: QQ-plot for females β2 β1 0 1 2 0.1 0.3 0.5 Male Abalones Theoretical Quantiles Sample Quantiles Figure 7.4: R: QQ-plot for males 117
7.4.2 More on Assessing Normality Skewness The Normal distribution is symmetric about itβs mean. Hence if we observe asymmetry in our histogram, we might suspect deviation from Normality. To quantify this asymmetry, we use skewness. One method of estimating the skewness of a distribution from data is: π1=1 πβπ π=1(π₯πβ ξ³½π₯)3 [1 πβπ π=1(π₯πβ ξ³½π₯)2]3/2 This is the method-of-moments estimator for the distribution skewness parameter. A value close to 0 indicates low skewness (i.e. high symmetry). Positive values correspond to right-skew and negative values to left-skew. Kurtosis Kurtosis measures the thickness of the tails of a distribution. Positive kurtosis implies that the tails are βfatterβ than those of a Normal. Negative values indicate that the tails are βthinnerβ than those of a Normal. The method of moments estimator is π2=1 πβπ π=1(π₯πβ ξ³½π₯)4 [1 πβπ π=1(π₯πβ ξ³½π₯)2]2β3 Hypothesis tests for Normality The Shapiro-Wilk test and the Kolmogorov-Smirnov test are formal hypothesis tests with the following hypotheses: π»0βΆData follows a Normal distribution π»1βΆData does not follow a Normal distribution You can read more about them in the references, but take note that applying multiple tests leads to a higher Type I error. Moreover, a large small sample size will almost always reject π»0 because small deviations are being classed as significant. I advocate a more graphical approach in assessing Normality, especially since the solution to Non-normality (the bootstrap) is readily accessible today. Example 7.2 (Abalone Measurements).Let us apply the above computations to the abalone measurements. R code 118
library(DescTools) aggregate(viscera ~gender, data=abl, Skew, method=1) ## gender viscera ## 1 F 0.4060918 ## 2 M 0.2482997 aggregate(viscera ~gender, data=abl, Kurt, method=1) ## gender viscera ## 1 F -0.2431501 ## 2 M 1.1660593 # Shapiro-Wilk Test only for males: shapiro.test(x) ## ## Shapiro-Wilk normality test ## ## data: x ## W = 0.96779, p-value = 0.1878 Python code abl.groupby("gender").skew() ## viscera ## gender ## F 0.418761 ## M 0.256046 for i,df in abl.groupby('gender'): print(f"{df.gender.iloc[0]}:{df.viscera.kurt():.4f}") ## F: -0.1390 ## M: 1.4220 stats.shapiro(x) ## ShapiroResult(statistic=np.float64(0.9677872659314101), pvalue=np.float64(0.1878490793650714)) SAS output Although the skewness seems large for the female group, the Normality tests do not reject the null hypothesis (see Figure 7.5). 119
Figure 7.5: SAS: Normality tests 7.4.3 Paired Sample Test The data in a paired sample test also arises from two groups, but the two groups are not independent. A very common scenario that gives rise to this test is when the same subject receives both treatments. His/her measurement under each treatment gives rise to a measurement in each group. However, the measurements are no longer independent. Example 7.3 (Reaction time of drivers).Consider a study on 32 drivers sampled from a driving school. Each driver is put in a simulation of a driving situation, where a target flashes red and green at random periods. Whenever the driver sees red, he/she has to press a brake button. For each driver, the study is carried out twice - at one of the repetitions, the individual carries on a phone conversation while at the other, the driver listens to the radio. Each measurement falls under one of two groups - βphoneβ or βradioβ, but the measurements for driver πare clearly related. Some people might just have a slower/faster baseline reaction time! This is a situation where a paired sample test is appropriate, not an independent sample test. Formal Set-up Suppose that we observe π1,β¦,ππindependent observations from group 1 and π1,β¦,ππ independent observations from group 2. However the pair (ππ,ππ)are correlated. It is assumed that 120
ππβΌ π(π1,π2 1),π=1,β¦,π (7.3) ππβΌ π(π2,π2 2),π=1,β¦,π (7.4) We let π·π=ππβππfor π=1,β¦,π. It follows that π·πβΌπ(π1βπ2,π2 1+π2 2β2πππ£(ππ,ππ)) The null and alternative hypotheses are stated in terms of the distribution of π·π: π»0βΆ ππ·=0 π»1βΆ ππ·β 0 The test statistic for this test is: π2=ξ³½ π·β0 π /βπ where π 2=βπ π=1(π·πβξ³½ π·)2 (πβ1) Under π»β0, the test statistic π2βΌπ‘πβ1. When we use a software to apply the test above, it will typically also return a confidence interval, computed as ξ³½ π·Β±π‘πβ1,1βπΌ/2Γπ /βπ Example 7.4 (Heart Rate Before/After Treadmill).The following dataset comes from the textbook (Rosner 2015), where an individual recorded his heart rate before using a treadmill (baseline) and 5 minutes after use, for 12 days in 2006. R code To run the paired test, we use the same function t.test as earlier, but we set the argument paired. hr_df <- read.csv("data/health_promo_hr.csv") before <- hr_df$baseline after <- hr_df$after5 t.test(before, after, paired=TRUE) Paired t-test data: before and after t = -21.714, df = 11, p-value = 2.209e-10 alternative hypothesis: true mean difference is not equal to 0 121
7.6 Summary While the test statistics are shown in detail, we do not need the full details for our class. I should also point out that the definitions of the test statistic in Section 7.5.1 and Section 7.5.2 were both taken from Rosner (2015). However, take note that different software have slightly different implementations, for instance in how they deal with ties. As always, my advice is to read the documentation as much as possible, and then to use the output of the tests as a guide to your decision-making (instead of treating them as the absolute truth). 7.7 References 7.7.1 Website References 1. UCI full abalone dataset: The dataset in the examples above, starting from Example 7.1, consists of samples from the full dataset. 2. Inference recap from Penn State: β’Hypothesis testing recap β’Confidence intervals recap 3. Tests for Normality More information on the Kolmogorov-Smirnov and Shapiro-Wilks Tests for Normality. 4. Overview of π‘-tests This page includes the rule of thumb about deciding when to use the equal variance test, and when to use the unequal variances version. 5. SAS vs. R/Python This link provides an explanation why the WRS test statistic for SAS is different from R in Example 7.5. 7.8 Exercises 1. List the different methods of assessing Normality. 2. Compute skewness for all variables in the concrete data set. 3. Compute π
1, the test statistic for the Wilcoxon Rank Sum Test, using R and Python. 4. Compute kurtosis for the chem data from chapter 5. Remove the outliers and recompute. 5. Perform the 2-sample t-test for G3 scores, comparing scores for Medu=1 to Medu=4. 128
8 ANOVA 8.1 Introduction In the previous topic, we learned how to run two-sample π‘-tests. The objective of these procedures is to compare the means from two groups. Frequently, however, the means of more than two groups need to be compared. In this topic, we introduce the one-way analysis of variance (ANOVA). It generalises the π‘-test methodology to more than 2 groups. Hypothesis tests in the ANOVA framework require the assumption of Normality. When this does not hold, we turn to the Kruskal-Wallis test - a non-parametric version of ANOVA, to compare distributions between groups. While the πΉ-test in ANOVA provides a determination of whether or not the group means are different, in practice, we would always want to follow up with specific comparisons between groups as well. This chapter also covers how we can construct confidence intervals in those cases. Example 8.1 (Effect of Antibiotics).The following example is taken from EkstrΓΈm and SΓΈrensen (2015). An experiment with dung from heifers1was carried out in order to explore the influence of antibiotics on the decomposition of dung organic material. As part of the experiment, 36 heifers were randomly assigned into six groups. Antibiotics of different types were added to the feed for heifers in five of the groups. The remaining group served as a control group. A bag of dung from each heifer was dug into the soil, and after 8 weeks, the amount of organic material remaining in each bag was measured. Figure 8.1 contains a boxplot of the data from each group. Compared to the control group, it does appear that the median organic weight of the dung from the other heifer groups is higher. The following table displays the mean, standard deviation, and count from each group: type mean sd count 1 Control 2.603 0.119 6 2 Alfacyp 2.895 0.117 6 3 Enroflox 2.710 0.162 6 4 Fenbenda 2.833 0.124 6 5 Ivermect 3.002 0.109 6 6 Spiramyc 2.855 0.054 4 Observe that the Spiramycin group only yielded 4 readings instead of 6. Our goal in this topic is to apply a technique for assessing if group means are statistically different from one another. Here are the specific analyses that we shall carry out: 1A heifer is a young, female cow that has not had her first calf yet. 129
Organic Weight after 8 weeks Antibiotics Organic material remaning 2.4 2.6 2.8 3.0 Control Alfacyp Enroflox Fenbenda Ivermect Spiramyc Figure 8.1: Boxplot for heifers data 130
1. Is there any significant difference, at 5% level, between the mean decomposition level of the groups? 2. At 5% level, is the mean level for Enrofloxacin different from the control group? 3. Pharmacologically speaking, Ivermectin and Fenbendazole are similar to each other. Let us call this sub-group (A). They work differently than Enrofloxacin. At 5% level, is there a significant difference between the mean from sub-group A and Enrofloxacin? 8.2 One-Way Analysis of Variance 8.2.1 Formal Set-up Suppose there are πgroups with ππobservations in the π-th group. The π-th observation in the π-th group will be denoted by πππ. In the One-Way ANOVA, we assume the following model: πππ =π+πΌπ+πππ,π=1,β¦,π,π=1,β¦,ππ(8.1) β’πis a constant, representing the underlying mean of all groups taken together. β’πΌπis a constant specific to the π-th group. It represents the difference between the mean of the π-th group and the overall mean. β’πππ represents random error about the mean π+πΌπfor an individual observation from the π-th group. In terms of distributions, we assume that the πππare i.i.d from a Normal distribution with mean 0 and variance π2. This leads to the following model for each observation: πππ βΌπ(π+πΌπ,π2)(8.2) It is not possible to estimate both πand all the πdifferent πΌπβs, since we only have πobserved mean values for the πgroups. For identifiability purposes, we need to constrain the parameters. There are two common constraints used, and note that different software have different defaults: 1. Setting βπ π=1πΌπ=0, or 2. Setting the reference level πΌ1=0. Continuing on from Equation 8.2, let us denote the mean for the π-th group as ππ, and the overall mean of all observations as π. We can then write the deviation of an individual observation from the overall mean as: πππβπ =(πππβππ) βββββ within +(ππβπ) β between (8.3) The first term on the right of the above equation is the source of within-group variability. The second term on the right gives rise to between-group variability. The intuition behind the ANOVA procedure is that if the between-group variability is large and the within-group variability is small, then we have evidence that the group means are different. If we square both sides of Equation 8.3 and sum over all observations, we arrive at the following equation, the essence of ANOVA: 131
π β π=1 ππ β π=1(πππβπ)2=π β π=1 ππ β π=1(πππβππ)2+π β π=1 ππ β π=1(ππβπ)2 The squared sums above are referred to as: πππ=πππ+πππ΅ β’πππ: Sum of Squares Total, β’πππ: Sum of Squares Within, and β’πππ΅: Sum of Squares Between. In addition the following definitions are important for understanding the ANOVA output: 1. The Between Mean Square: πππ΅=πππ΅ πβ1 2. The Within Mean Square: πππ=πππ πβπ The mean squares are estimates of the variability between and within groups. The ratio of these quantities is the test statistic. 8.2.2 πΉ-Test in One-Way ANOVA The null and alternative hypotheses are: π»0βΆ πΌπ=0for all π π»1βΆ πΌπβ 0for at least one π The test statistic is given by πΉ= πππ΅ πππ Under π»0, the statistic πΉfollows an πΉdistribution with πβ1and πβπdegrees of freedom. 8.2.3 Assumptions These are the assumptions that will need to be validated. 1. The observations are independent of each other. This is usually a characteristic of the design of the experiment, and is not something we can always check from the data. 2. The errors are Normally distributed. Residuals can be calculated as follows: πππβππ The distribution of these residuals should be checked for Normality. 132
3. The variance within each group is the same. In ANOVA, the πππis a pooled estimate (across the groups) that is used; in order for this to be valid, the variance within each group should be identical. Just as in the 2-sample situation, we shall avoid separate hypotheses tests and proceed with the rule-of-thumb that if the ratio of the largest to smallest standard deviation is less than 2, we can proceed with the analysis. Example 8.2 (F-test for Heifers Data).We begin by applying the overall πΉ-test to the heifers data, to assess if there is any significant difference between the means. R code #R heifers <- read.csv("data/antibio.csv") u_levels <- sort(unique(heifers$type)) heifers$type <- factor(heifers$type, levels=u_levels[c(2,1,3,4,5,6)]) heifers_lm <- lm(org ~type, data=heifers) anova(heifers_lm) Analysis of Variance Table Response: org Df Sum Sq Mean Sq F value Pr(>F) type 5 0.59082 0.118165 7.9726 8.953e-05 *** Residuals 28 0.41500 0.014821 --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Python code #Python import pandas as pd import numpy as np from scipy import stats import statsmodels.api as sm from statsmodels.formula.api import ols heifers =pd.read_csv("data/antibio.csv") heifer_lm =ols('org ~ type', data=heifers).fit() anova_tab =sm.stats.anova_lm(heifer_lm, type=3,) print(anova_tab) df sum_sq mean_sq F PR(>F) type 5.0 0.590824 0.118165 7.972558 0.00009 Residual 28.0 0.415000 0.014821 NaN NaN 133
SAS output Figure 8.2: SAS: F-test for heifers data At the 5% significance level, we reject the null hypothesis to conclude that the group means are significantly different from one another. This answers question (1) from Example 8.1. To extract the estimated parameters, we can use the following code: R code # R summary(heifers_lm) Call: lm(formula = org ~ type, data = heifers) Residuals: Min 1Q Median 3Q Max -0.29000 -0.06000 0.01833 0.07250 0.18667 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 2.60333 0.04970 52.379 < 2e-16 *** typeAlfacyp 0.29167 0.07029 4.150 0.000281 *** typeEnroflox 0.10667 0.07029 1.518 0.140338 typeFenbenda 0.23000 0.07029 3.272 0.002834 ** typeIvermect 0.39833 0.07029 5.667 4.5e-06 *** typeSpiramyc 0.25167 0.07858 3.202 0.003384 ** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 0.1217 on 28 degrees of freedom Multiple R-squared: 0.5874, Adjusted R-squared: 0.5137 F-statistic: 7.973 on 5 and 28 DF, p-value: 8.953e-05 Python code 134
# Python print(heifer_lm.summary()) OLS Regression Results ============================================================================== Dep. Variable: org R-squared: 0.587 Model: OLS Adj. R-squared: 0.514 Method: Least Squares F-statistic: 7.973 Date: Thu, 18 Dec 2025 Prob (F-statistic): 8.95e-05 Time: 05:46:34 Log-Likelihood: 26.655 No. Observations: 34 AIC: -41.31 Df Residuals: 28 BIC: -32.15 Df Model: 5 Covariance Type: nonrobust ==================================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------------ Intercept 2.8950 0.050 58.248 0.000 2.793 2.997 type[T.Control] -0.2917 0.070 -4.150 0.000 -0.436 -0.148 type[T.Enroflox] -0.1850 0.070 -2.632 0.014 -0.329 -0.041 type[T.Fenbenda] -0.0617 0.070 -0.877 0.388 -0.206 0.082 type[T.Ivermect] 0.1067 0.070 1.518 0.140 -0.037 0.251 type[T.Spiramyc] -0.0400 0.079 -0.509 0.615 -0.201 0.121 ============================================================================== Omnibus: 2.172 Durbin-Watson: 2.146 Prob(Omnibus): 0.338 Jarque-Bera (JB): 1.704 Skew: -0.545 Prob(JB): 0.427 Kurtosis: 2.876 Cond. No. 6.71 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. 135
SAS output Figure 8.3: SAS: Group summaries for heifers data When estimating, both R and Python set one of the πΌπto be equal to 0. In the case of R, it is the coeο¬icient for Control, since we set it as the first level in the factor. For Python, we can tell from the output that the constraint has been placed on the coeο¬icient for Alfacyp (since it is missing). However, all estimates are group means are identical. From the R output, we can compute that the estimate of the mean for the Alfacyp group is 2.603+0.292=2.895 From the Python output, we can read off (the Intercept term) that the estimate for Alfacyp is precisely 2.895+0=2.895 To check the assumptions, we can use the following code, which results in the two plots Figure 8.4 and Figure 8.5. R code # R r1 <- residuals(heifers_lm) hist(r1) qqnorm(r1); qqline(r1) Python code 136
Histogram of r1 r1 Frequency β0.3 β0.2 β0.1 0.0 0.1 0.2 0246 Figure 8.4: R: Histogram for heifers β2 β1 0 1 2 β0.3 β0.1 0.1 Normal QβQ Plot Theoretical Quantiles Sample Quantiles Figure 8.5: R: QQ-plot for heifers # Python import matplotlib.pyplot as plt f, axs =plt.subplots(1,2, figsize=(8,4)) tmp =plt.subplot(121) heifer_lm.resid.hist(); tmp =plt.subplot(122) sm.qqplot(heifer_lm.resid, line="q", ax=tmp); 0.3 0.2 0.1 0.0 0.1 0.2 0 1 2 3 4 5 6 1 0 1 Theoretical Quantiles 0.3 0.2 0.1 0.0 0.1 0.2 Sample Quantiles Figure 8.6: Py: Normality checks for heifers For SAS, we have to create a new column containing the residuals in a temporary dataset before creating these plots. 137
8.6 Kruskal-Wallis Procedure If the assumptions of the ANOVA procedure are not met, we can turn to a non-parametric version - the Kruskal Wallis test. This latter procedure is a generalisation of the Wilcoxon Rank-Sum test for 2 independent samples. 8.6.1 Formal Set-up The test statistic compares the average ranks in the individual groups. If these are close together, we would be inclined to conclude the treatments are equally effective. The null hypothesis is that all groups follow the same distribution. The alternative hypothesis is that at least one of the groupsβ distribution differs from another by a location shift. We then proceed with: 1. Pool the observations over all samples, thus constructing a combined sample of size π= βππ. Assign ranks to individual observations, using average rank in the case of tied observations. Compute the rank sum π
πfor each of the πsamples. 2. If there are no ties, compute the test statistic as π»= 12 π(π+1) π β π=1 π
2 π ππβ3(π+1) 3. If there are ties, compute the test statistic as π»β=π» 1ββπ π=1(π‘3 πβπ‘π) π3βπ where π‘πrefers to the number of observations with the same value in the π-th cluster of tied observations and πis the number of tied groups. Under π»0, the test statistic follows a π2distribution with πβ1degrees of freedom. ΔΊImportant This test should only be used if ππβ₯5for all groups. Example 8.5 (Kruskal-Wallis Test).Here is the code and output from running the Kruskal- Wallis test in the three software. R code kruskal.test(heifers$org, heifers$type) Kruskal-Wallis rank sum test data: heifers$org and heifers$type Kruskal-Wallis chi-squared = 19.645, df = 5, p-value = 0.001457 144
Python code out =[x[1]for xin heifers.org.groupby(heifers.type)] kw_out =stats.kruskal(*out) print(f"""The test statistic is {kw_out.statistic:.3f}, the p-value is {kw_out.pvalue:.3f}.""") The test statistic is 19.645, the p-value is 0.001. SAS output Figure 8.9: SAS: Kruskal-Wallis output, heifers data 8.7 Summary The purpose of this topic was to introduce you to the one-way ANOVA model. While there are restrictive distributional assumptions that it entails, I once again urge you to focus on the information the method conveys. It attempts to compare the within-group variance to the between-group variance. Try to avoid viewing statistical procedures as flowcharts. If an assumption does not hold, or a p-value is borderline significant, or try to identify which points lead to the result being significant (or not). Our job as analysts does not end after reporting the p-value from the πΉ-test. We should try to dig deeper to uncover which groups are the ones that are different from the rest. 145
Finally, take note that we should specify the contrasts we wish to test/estimate upfront, even before collecting the data. Only the Tukey comparison method (HSD) is valid if we perform multiple comparisons after inspecting the data. Most of the theoretical portions in this topic were taken from the textbook Rosner (2015). 8.8 References 8.8.1 Website References 1. Welchβs ANOVA This website discusses an alternative test when the equal variance assumption has not been satisfied. It is for information only; it will not be tested. 2. scipy stats This website contains documentation on the distribution-related functions that we might need from scipy stats, e.g. retrieving quantiles. 3. Contrast coding: More information about how to set the constraints for estimation in R. 4. Type I,II,III SS: When working with ANOVA (especially with unbalanced models), you may come across different types of Sum of Squares. You will learn more about this in ST4233. 8.8.2 Exercises 1. Compare the formula for confidence intervals in Section 8.3 with the formula in Section 7.4.1. How are they different? 2. Consider the formula for test statistic in the F-test. Can you conceive of a robust version of it? 3. Assess if the average of (Alfacyp, Enroflox, Spiramycin) is significantly different from (Ivermectin, Fenbendazole) at 5% significance level. 4. Apply the Bonferroni correction to the following two comparisons: 1. Alfacyp vs. Ivermectin 2. Enrofloxacin vs. Fenbendazonle 5. Apply the ANOVA F-test to the G3 scores, by Medu, for the student performance dataset. 146
9 Linear Regression 9.1 Introduction Regression analysis is a technique for investigating and modeling the relationship between variables like X and Y. Here are some examples: 1. Within a country, we may wish to use per capita income (X) to estimate the life expectancy (Y) of residents. 2. We may wish to use the size of a crab claw (X) to estimate the closing force that it can exert (Y). 3. We may wish to use the height of a person (X) to estimate their weight (Y). In all the above cases, we refer to πas the explanatory or independent variable. It is also sometimes referred to as a predictor. πis referred to as the response or dependent variable. In this topic, we shall first introduce the case of simple linear regression, where we model the π on a single π. In later sections, we shall model the πon multiple πβs. This latter technique is referred to as multiple linear regression. Regression models are used for two primary purposes: 1. To understand how certain explanatory variables affect the response variable. This aim is typically known as estimation, since the primary focus is on estimating the unknown parameters of the model. 2. To predict the response variable for new values of the explanatory variables. This is referred to as prediction. In our course, we shall focus on the estimation aim, since prediction models require a paradigm of their own, and are best learnt alongside a larger suite of models e.g. decision trees, support vector machines, etc. Example 9.1 (Concrete Data: Flow on Water).Recall the concrete dataset that we first encountered in Example 3.6. The fitted regression model, that estimates the relationship between the output of the flow test, and the amount of water used to create the concrete, is shown in Figure 9.1. Note that trend in the scatterplot in Figure 9.1. In this topic, we shall figure out how to estimate this line in this topic. Example 9.2 (Bike Rental Data).In the introduction to SAS, we encountered data on bike rentals in the USA over a period of 2 years. Here, we shall attempt to model the number of registered users on the number of casual users. Contingent on whether the day is a working one or not, it does appear that the trendline is different (see Figure 9.2). 147
Concrete data Water FLOW.cm. 20 30 40 50 60 70 80 160 180 200 220 240 Figure 9.1: Scatterplot with simple linear regression model Registered vs. Casual, by Working Day Status casual registered 0 2000 4000 6000 0 1000 2000 3000 no yes Figure 9.2: Scatterplot of registered vs. casual bike renters 148
9.2 Simple Linear Regression 9.2.1 Formal Set-up The simple linear regression model is applicable when we have observations (ππ,ππ)for π individuals. For now, letβs assume both the πand πvariables are quantitative. The simple linear regression model is given by ππ=π½0+π½1ππ+ππ(9.1) where β’π½0is the intercept term, β’π½1is the slope, and β’ππis an error term, specific to each individual in the dataset. π½0and π½1are unknown constants that need to be estimated from the data. There is an implicit assumption in the formulation of the model that there is a linear relationship between ππand ππ. In terms of distributions, we assume that the ππare i.i.d Normal. ππβΌπ(0,π2),π=1β¦,π (9.2) The constant variance assumption is also referred to as homoscedasticity (homo-ski-das-ti-city). The validity of the above assumptions will have to be checked after the model is fitted. All in all, the assumptions imply that: 1. πΈ(ππ|ππ)=π½0+π½1ππ, for π=1,β¦,π. 2. πππ(ππ|ππ)=πππ(ππ)=π2, for π=1,β¦,π. 3. The ππare independent. 4. The ππβs are Normally distributed. 9.2.2 Estimation Before deploying or using the model, we need to estimate optimal values to use for the unknown π½0and π½1. We shall introduce the method of Ordinary Least Squares (OLS) for the estimation. Let us define the error Sum of Squares to be πππΈ=π(π½0,π½1)= π β π=1(ππβπ½0βπ½1ππ)2(9.3) Then the OLS estimates of π½0and π½1are given by arg min π½0,π½1 π β π=1(ππβπ½0βπ½1ππ)2 The minimisation above can be carried out analytically, by taking partial derivative with respect to the two parameters and setting them to 0. 149
ππ ππ½0= β2 π β π=1(ππβπ½0βπ½1ππ)=0 ππ ππ½1= β2 π β π=1ππ(ππβπ½0βπ½1ππ)=0 Solving and simplifying, we arrive at the following: ξ» π½1=βπ π=1(ππβξ³½ π)(ππβξ³½ π) βπ π=1(ππβξ³½ π)2 ξ» π½0=ξ³½ πβ ξ» π½0ξ³½ π where ξ³½ π =(1/π)βππand ξ³½ π=(1/π)βππ. If we define the following sums: πππ =π β π=1ππππβ(βπ π=1ππ)(βπ π=1ππ) π πππ =π β π=1π2 πβ(βπ π=1ππ)2 π then a form convenient for computation of ξ» π½1is ξ» π½1=πππ πππ Once we have the estimates, we can use Equation 9.1 to compute fitted values for each observation. These correspond to our best guess of the mean of the distributions from which the observations arose: ξ» ππ=ξ» π½0+ξ» π½1ππ, π=1,β¦,π As always, we can form residuals as the deviations from fitted values. ππ=ππβξ» ππ(9.4) Residuals are our best guess at the unobserved error terms ππ. Squaring the residuals and summing over all observations, we can arrive at the following decomposition, which is very similar to the one in the ANOVA model: π β π=1(ππβξ³½ π)2 βββββ πππ =π β π=1(ππβξ» ππ)2 βββββ πππ
ππ +π β π=1(ξ» ππβξ³½ π)2 βββββ πππ
ππ where β’πππis known as the total sum of squares. β’πππ
ππ is known as the residual sum of squares. β’πππ
ππ is known as the regression sum of squares. 150
In our model, recall from Equation 9.2 that we had assumed equal variance for all our observations. We can estimate π2with ξ» π2=πππ
ππ πβ2 Our distributional assumptions lead to the following for our estimates ξ» π½0and ξ» π½1: ξ» π½0βΌ π(π½0,π2(1/π+ ξ³½ π2/πππ)) (9.5) ξ» π½1βΌ π(π½1,π2/πππ)(9.6) The above are used to construct confidence intervals for π½0and π½1, based on π‘-distributions. 9.3 Hypothesis Test for Model Significance The first test that we introduce here is to test if the coeο¬icient π½1is significantly different from 0. It is essentially a test of whether it was worthwhile to use a regression model of the form in Equation 9.1, instead of a simple mean to represent the data. The null and alternative hypotheses are: π»0βΆ π½1=0 π»1βΆ π½1β 0 The test statistic is πΉ0=πππ
ππ/1 πππ
ππ /(πβ2) (9.7) Under the null hypothesis, πΉ0βΌπΉ1,πβ2. It is also possible to perform this same test as a π‘-test, using the result earlier. The statement of the hypotheses is equivalent to the πΉ-test. The test statistic π0=ξ» π½1 βξ» π2/πππ (9.8) Under π»0, the distribution of π0is π‘πβ2. This π‘-test and the earlier πΉ-test in this section are identical. It can be proved that πΉ0=π2 0; the obtained π-values will be identical. 151
9.3.1 Coeο¬icient of Determination, π
2 The coeο¬icient of determination π
2is defined as π
2=1βπππ
ππ πππ=πππ
ππ πππ It can be interpreted as the proportion of variation in ππ, explained by the inclusion of ππ. Since 0β€πππ
ππ β€πππ, we can easily prove that 0β€π
2β€1. The larger the value of π
2is, the better the model is. When we get to the case of multiple linear regression, take note that simply including more variables in the model can increase π
2. This is undesirable; it is preferable to have a parsimonious model that explains the response variable well. Example 9.3 (Concrete Data Model).In this example, we focus on the estimation of the model parameters for the two variables we introduced in Example 9.1 R code #R concrete <- read.csv("data/concrete+slump+test/slump_test.data") names(concrete)[c(1,11)] <- c("id","Comp.Strength") lm_flow_water <- lm(FLOW.cm. ~Water, data=concrete) summary(lm_flow_water) Call: lm(formula = FLOW.cm. ~ Water, data = concrete) Residuals: Min 1Q Median 3Q Max -37.211 -10.836 2.734 11.031 22.163 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -58.72755 13.28635 -4.420 2.49e-05 *** Water 0.54947 0.06704 8.196 8.10e-13 *** --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 13.68 on 101 degrees of freedom Multiple R-squared: 0.3995, Adjusted R-squared: 0.3935 F-statistic: 67.18 on 1 and 101 DF, p-value: 8.097e-13 Python code 152
#Python import pandas as pd import numpy as np import statsmodels.api as sm from statsmodels.formula.api import ols concrete =pd.read_csv("data/concrete+slump+test/slump_test.data") concrete.rename(columns={'No':'id', 'Compressive Strength (28-day)(Mpa)':'Comp_Strength', 'FLOW(cm)':'Flow'}, inplace=True) lm_flow_water =ols('Flow ~ Water', data=concrete).fit() print(lm_flow_water.summary()) OLS Regression Results ============================================================================== Dep. Variable: Flow R-squared: 0.399 Model: OLS Adj. R-squared: 0.394 Method: Least Squares F-statistic: 67.18 Date: Mon, 22 Dec 2025 Prob (F-statistic): 8.10e-13 Time: 05:24:14 Log-Likelihood: -414.60 No. Observations: 103 AIC: 833.2 Df Residuals: 101 BIC: 838.5 Df Model: 1 Covariance Type: nonrobust ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ Intercept -58.7276 13.286 -4.420 0.000 -85.084 -32.371 Water 0.5495 0.067 8.196 0.000 0.416 0.682 ============================================================================== Omnibus: 6.229 Durbin-Watson: 1.843 Prob(Omnibus): 0.044 Jarque-Bera (JB): 5.873 Skew: -0.523 Prob(JB): 0.0530 Kurtosis: 2.477 Cond. No. 1.95e+03 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 1.95e+03. This might indicate that there are strong multicollinearity or other numerical problems. 153