Advanced R Statistical Programming and Data Models: Analysis, Machine Learning, and Visualization 9781484228715

Carry out a variety of advanced statistical analyses including generalized additive models, mixed effects models, multip

1,882 329 70MB

English Pages 649 Year 2019

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Advanced R Statistical Programming and Data Models: Analysis, Machine Learning, and Visualization
 9781484228715

Table of contents :
Front Matter ....Pages i-xx
Univariate Data Visualization (Matt Wiley, Joshua F. Wiley)....Pages 1-31
Multivariate Data Visualization (Matt Wiley, Joshua F. Wiley)....Pages 33-59
GLM 1 (Matt Wiley, Joshua F. Wiley)....Pages 61-122
GLM 2 (Matt Wiley, Joshua F. Wiley)....Pages 123-164
GAMs (Matt Wiley, Joshua F. Wiley)....Pages 165-224
ML: Introduction (Matt Wiley, Joshua F. Wiley)....Pages 225-249
ML: Unsupervised (Matt Wiley, Joshua F. Wiley)....Pages 251-303
ML: Supervised (Matt Wiley, Joshua F. Wiley)....Pages 305-382
Missing Data (Matt Wiley, Joshua F. Wiley)....Pages 383-433
GLMMs: Introduction (Matt Wiley, Joshua F. Wiley)....Pages 435-477
GLMMs: Linear (Matt Wiley, Joshua F. Wiley)....Pages 479-552
GLMMs: Advanced (Matt Wiley, Joshua F. Wiley)....Pages 553-586
Modelling IIV (Matt Wiley, Joshua F. Wiley)....Pages 587-611
Back Matter ....Pages 613-638

Citation preview

Advanced R Statistical Programming and Data Models Analysis, Machine Learning, and Visualization — Matt Wiley Joshua F. Wiley

Advanced R Statistical Programming and Data Models Analysis, Machine Learning, and Visualization

Matt Wiley Joshua F. Wiley

Advanced R Statistical Programming and Data Models: Analysis, Machine Learning, and Visualization Matt Wiley Columbia City, IN, USA

Joshua F. Wiley Columbia City, IN, USA

ISBN-13 (pbk): 978-1-4842-2871-5      ISBN-13 (electronic): 978-1-4842-2872-2 https://doi.org/10.1007/978-1-4842-2872-2 Library of Congress Control Number: 2019932986

Copyright © 2019 by Matt Wiley and Joshua F. Wiley This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Steve Anglin Development Editor: Matthew Moodie Coordinating Editor: Mark Powers Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail [email protected]; for reprint, paperback, or audio rights, please email [email protected]. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book's product page, located at www.apress.com/9781484228715. For more detailed information, please visit http://www.apress.com/source-code. Printed on acid-free paper

Table of Contents About the Authors���������������������������������������������������������������������������������������������������� ix About the Technical Reviewer��������������������������������������������������������������������������������� xi Acknowledgments������������������������������������������������������������������������������������������������� xiii Introduction�������������������������������������������������������������������������������������������������������������xv Chapter 1: Univariate Data Visualization������������������������������������������������������������������ 1 1.1 Distribution����������������������������������������������������������������������������������������������������������������� 2 Visualizing the Observed Distribution������������������������������������������������������������������������������������ 2 Stacked Dot Plots and Histograms����������������������������������������������������������������������������������������� 2 Density Plots�������������������������������������������������������������������������������������������������������������������������� 6 Comparing the Observed Distribution with Expected Distributions��������������������������������������� 9 Q-Q Plots�������������������������������������������������������������������������������������������������������������������������������� 9 Density Plots������������������������������������������������������������������������������������������������������������������������ 14 Fitting More Distributions���������������������������������������������������������������������������������������������������� 15

1.2 Anomalous Values���������������������������������������������������������������������������������������������������� 21 1.3 Summary������������������������������������������������������������������������������������������������������������������ 30 Chapter 2: Multivariate Data Visualization������������������������������������������������������������� 33 2.1 Distribution��������������������������������������������������������������������������������������������������������������� 34 2.2 Anomalous Values���������������������������������������������������������������������������������������������������� 40 2.3 Relations Between Variables������������������������������������������������������������������������������������ 44 Assessing Homogeneity of Variance������������������������������������������������������������������������������������ 53

2.4 Summary������������������������������������������������������������������������������������������������������������������ 59

iii

Table of Contents

Chapter 3: GLM 1���������������������������������������������������������������������������������������������������� 61 3.1 Conceptual Background������������������������������������������������������������������������������������������� 62 3.2 Categorical Predictors and Dummy Coding�������������������������������������������������������������� 65 Two-Level Categorical Predictors���������������������������������������������������������������������������������������� 65 Three- or More Level Categorical Predictors����������������������������������������������������������������������� 66

3.3 Interactions and Moderated Effects������������������������������������������������������������������������� 68 3.4 Formula Interface����������������������������������������������������������������������������������������������������� 70 3.5 Analysis of Variance������������������������������������������������������������������������������������������������� 72 Conceptual Background������������������������������������������������������������������������������������������������������� 72 ANOVA in R��������������������������������������������������������������������������������������������������������������������������� 76

3.6 Linear Regression���������������������������������������������������������������������������������������������������� 79 Conceptual Background������������������������������������������������������������������������������������������������������� 80 Linear Regression in R��������������������������������������������������������������������������������������������������������� 82 High-Performance Linear Regression���������������������������������������������������������������������������������� 99

3.7 Controlling for Confounds��������������������������������������������������������������������������������������� 102 3.8 Case Study: Multiple Linear Regression with Interactions������������������������������������� 113 3.9 Summary���������������������������������������������������������������������������������������������������������������� 121 Chapter 4: GLM 2�������������������������������������������������������������������������������������������������� 123 4.1 Conceptual Background����������������������������������������������������������������������������������������� 124 Logistic Regression������������������������������������������������������������������������������������������������������������ 124 Count Regression��������������������������������������������������������������������������������������������������������������� 126

4.2 R Examples������������������������������������������������������������������������������������������������������������� 128 Binary Logistic Regression������������������������������������������������������������������������������������������������ 129 Ordered Logistic Regression���������������������������������������������������������������������������������������������� 136 Multinomial Logistic Regression���������������������������������������������������������������������������������������� 140 Poisson and Negative Binomial Regression����������������������������������������������������������������������� 145

4.3 Case Study: Multinomial Logistic Regression�������������������������������������������������������� 153 4.4 Summary���������������������������������������������������������������������������������������������������������������� 162

iv

Table of Contents

Chapter 5: GAMs��������������������������������������������������������������������������������������������������� 165 5.1 Conceptual Overview��������������������������������������������������������������������������������������������� 166 Smoothing Splines������������������������������������������������������������������������������������������������������������� 167

5.2 GAMs in R��������������������������������������������������������������������������������������������������������������� 173 Gaussian Outcomes����������������������������������������������������������������������������������������������������������� 173 Binary Outcomes���������������������������������������������������������������������������������������������������������������� 202 Unordered Outcomes��������������������������������������������������������������������������������������������������������� 209 Count Outcomes����������������������������������������������������������������������������������������������������������������� 214

5.3 Summary���������������������������������������������������������������������������������������������������������������� 223 Chapter 6: ML: Introduction���������������������������������������������������������������������������������� 225 6.1 Training and Validation Data����������������������������������������������������������������������������������� 226 6.2 Resampling and Cross-­Validation�������������������������������������������������������������������������� 233 6.3 Bootstrapping��������������������������������������������������������������������������������������������������������� 237 6.4 Parallel  Processing and Random Numbers������������������������������������������������������������ 239 foreach������������������������������������������������������������������������������������������������������������������������������� 245

6.5 Summary���������������������������������������������������������������������������������������������������������������� 247 Chapter 7: ML: Unsupervised�������������������������������������������������������������������������������� 251 7.1 Data Background and Exploratory Analysis������������������������������������������������������������ 252 7.2 kmeans������������������������������������������������������������������������������������������������������������������� 263 7.3 Hierarchical Clusters���������������������������������������������������������������������������������������������� 276 7.4 Principal Component Analysis�������������������������������������������������������������������������������� 288 7.5 Non-linear Cluster Analysis������������������������������������������������������������������������������������ 300 7.6 Summary���������������������������������������������������������������������������������������������������������������� 302 Chapter 8: ML: Supervised����������������������������������������������������������������������������������� 305 8.1 Data Preparation���������������������������������������������������������������������������������������������������� 306 One Hot Encoding��������������������������������������������������������������������������������������������������������������� 308 Scale and Center���������������������������������������������������������������������������������������������������������������� 311 Transformations����������������������������������������������������������������������������������������������������������������� 312 Train vs. Validation Data����������������������������������������������������������������������������������������������������� 318 Principal Component Analysis�������������������������������������������������������������������������������������������� 319 v

Table of Contents

8.2 Supervised Learning Models���������������������������������������������������������������������������������� 324 Support Vector Machines��������������������������������������������������������������������������������������������������� 325 Classification and Regression Trees���������������������������������������������������������������������������������� 335 Random Forests����������������������������������������������������������������������������������������������������������������� 341 Stochastic Gradient Boosting��������������������������������������������������������������������������������������������� 348 Multilayer Perceptron��������������������������������������������������������������������������������������������������������� 358

8.3 Summary���������������������������������������������������������������������������������������������������������������� 380 Chapter 9: Missing Data��������������������������������������������������������������������������������������� 383 9.1 Conceptual Background����������������������������������������������������������������������������������������� 384 Multiple Imputation������������������������������������������������������������������������������������������������������������ 386

9.2 R Examples������������������������������������������������������������������������������������������������������������� 393 Multiple Imputation with Regression��������������������������������������������������������������������������������� 398 Multiple Imputation with Parallel Processing�������������������������������������������������������������������� 410 Multiple Imputation Using Random Forests����������������������������������������������������������������������� 412

9.3 Case Study: Multiple Imputation with RFs�������������������������������������������������������������� 419 9.4 Summary���������������������������������������������������������������������������������������������������������������� 432 Chapter 10: GLMMs: Introduction������������������������������������������������������������������������� 435 10.1 Multilevel Data����������������������������������������������������������������������������������������������������� 436 Reshaping Data��������������������������������������������������������������������������������������������������������������� 438 Daily Dataset�������������������������������������������������������������������������������������������������������������������� 440

10.2 Descriptive Statistics������������������������������������������������������������������������������������������� 444 Basic Descriptives����������������������������������������������������������������������������������������������������������� 446 Intraclass Correlation Coefficient (ICC)���������������������������������������������������������������������������� 454

10.3 Exploration and Assumptions������������������������������������������������������������������������������� 457 Distribution and Outliers�������������������������������������������������������������������������������������������������� 457 Time Trends��������������������������������������������������������������������������������������������������������������������� 463 Autocorrelation���������������������������������������������������������������������������������������������������������������� 465 Assumptions�������������������������������������������������������������������������������������������������������������������� 470

10.4 Summary�������������������������������������������������������������������������������������������������������������� 476 vi

Table of Contents

Chapter 11: GLMMs: Linear���������������������������������������������������������������������������������� 479 11.1 Theory������������������������������������������������������������������������������������������������������������������ 480 Generalized Linear Mixed Models������������������������������������������������������������������������������������ 480 Mixed Effects vs. Multilevel Model Terminology�������������������������������������������������������������� 485 Statistical Inference��������������������������������������������������������������������������������������������������������� 485 Effect Sizes���������������������������������������������������������������������������������������������������������������������� 487 Random Intercept Model������������������������������������������������������������������������������������������������� 489 Visualizing Random Effects��������������������������������������������������������������������������������������������� 489 Interpreting Random Intercept Models���������������������������������������������������������������������������� 494 Random Intercept and Slope Model��������������������������������������������������������������������������������� 502 Intercepts and Slopes as Outcomes�������������������������������������������������������������������������������� 508

11.2 R Examples����������������������������������������������������������������������������������������������������������� 514 Linear Mixed Model with Random Intercept�������������������������������������������������������������������� 514 Linear Mixed Model with Random Intercept and Slope��������������������������������������������������� 528

11.3 Summary�������������������������������������������������������������������������������������������������������������� 549 Chapter 12: GLMMs: Advanced����������������������������������������������������������������������������� 553 12.1 Conceptual Background��������������������������������������������������������������������������������������� 554 12.2 Logistic GLMM������������������������������������������������������������������������������������������������������ 554 Random Intercept������������������������������������������������������������������������������������������������������������ 554 Random Intercept and Slope������������������������������������������������������������������������������������������� 560

12.3 Poisson and Negative Binomial GLMMs��������������������������������������������������������������� 565 Random Intercept������������������������������������������������������������������������������������������������������������ 565 Random Intercept and Slope������������������������������������������������������������������������������������������� 576

12.4 Summary�������������������������������������������������������������������������������������������������������������� 586

vii

Table of Contents

Chapter 13: Modelling IIV������������������������������������������������������������������������������������� 587 13.1 Conceptual Background��������������������������������������������������������������������������������������� 588 Bayesian Inference���������������������������������������������������������������������������������������������������������� 588 What Is IIV?���������������������������������������������������������������������������������������������������������������������� 589 Intra-individual Variability as a Predictor������������������������������������������������������������������������� 595 Software Implementation: VARIAN����������������������������������������������������������������������������������� 599

13.2 R Examples����������������������������������������������������������������������������������������������������������� 600 IIV Predicting a Continuous Outcome������������������������������������������������������������������������������ 600

13.3 Summary�������������������������������������������������������������������������������������������������������������� 610 Bibliography��������������������������������������������������������������������������������������������������������� 613 Index��������������������������������������������������������������������������������������������������������������������� 625

viii

About the Authors Matt Wiley is a tenured, associate professor of mathematics with awards in both mathematics education and honors student works. He earned degrees in pure mathematics, computer science, and business administration through the University of California and Texas A&M University Systems. He serves as director of quality enhancement at Victoria College, facilitating comprehensive assessment programs, key performance indicator dashboards and one-click reports, and data consultation for campus stakeholders. Outside academia, he is managing partner at Elkhart Group LLC, a statistical consultancy. With experience in programming R, SQL, C++, Ruby, Fortran, and JavaScript, he has always found ways to meld his passion for writing with his joy of logical problem solving and data science. From the boardroom to the classroom, Matt enjoys finding dynamic ways to partner with interdisciplinary and diverse teams to make complex ideas and projects understandable and solvable.  Joshua F. Wiley is a lecturer in the Monash Institute of Cognitive and Clinical Neurosciences and School of Psychological Sciences at Monash University. He earned his PhD from the University of California, Los Angeles, and completed his postdoctoral training in primary care and prevention. His research uses advanced quantitative methods to understand the dynamics between psychosocial factors, sleep, and other health behaviors in relation to psychological and physical health. He develops or codevelops a number of R packages including varian, a package to conduct Bayesian scale-location structural equation models, and MplusAutomation, a popular package that links R to the commercial Mplus software, and miscellaneous functions to explore data or speed up analysis in JWileymisc.  

ix

About the Technical Reviewer Andrew Moskowitz is an analytics and data science professional in the entertainment industry focused on understanding user behavior, marketing attribution and efficacy, and using advanced data science concepts to address business problems. He earned his PhD in quantitative psychology at the University of California, Los Angeles, where he focused on hypothesis testing and mixed effects models.  

xi

Acknowledgments To our dear family, who may not always understand everything we write, yet are nevertheless content to place our books on fireside mantels and coffee tables.

xiii

Introduction This book shows how to conduct data analysis using the popular R language. Our goal is to provide a practical resource for conducting advanced statistical analyses using R. As this is an advanced book, the reader is assumed to have some background in using R, including familiarity with general data management and the use of functions. Because the book is primarily practical, we do not provide in-depth theoretical or conceptual introductions to the various statistical models discussed. However, to aid understanding and their appropriate application, we do provide some conceptual background on each analytic technique discussed.

Conventions Bold lowercase letters are used to refer to a vector, for example, x. Bold uppercase letters are used to refer to a matrix, for example, X. Generally, the Latin alphabet is used for data and the Greek alphabet is used for parameters. Mathematical functions are indicated with parentheses, for example, f (·). In the text, reference to R code or function will be in monospaced font like this. R function names have parentheses included to help indicate it is a function, such as mean() to indicate the mean function in R.

Package Setup Throughout the book, we will make use of many different R packages that make tasks easier or provide more robust or sophisticated graphing and analysis options. Although not required for readers, we make use of the checkpoint package to help ensure the book is reproducible [23]. If you do not care about reproducibility and are happy to take your chances that our code that worked with one version of R and packages also works with whatever versions you have, then you can just skip reading this section. If you want reproducibility, but do not care why or how it works, then just create R scripts for the code for each chapter, save them, and then run the checkpoint package at the beginning. If you care and want to know why and how it all works, read on the next few paragraphs. xv

Introduction

Details on Reproducibility The many additional packages available for R are one of its greatest strengths. However, they also create some challenges. For example, as a reader, suppose that on your computer, you have R v3.4.3 installed and as part of that in January you had installed the ggplot2 package for graphs. By default, you will have whatever version of ggplot2 was available in January when you installed it. Now in one chapter, we tell you that you need both the ggplot2 and cowplot packages. Because you already had ggplot2 installed, you do not need to install it again. However, suppose that you did not have the cowplot package installed. So, whenever you happen to be reading that chapter, you attempt to install the cowplot package, let’s say it’s in April. You will now by default get the latest version of cowplot available for that version of R as of April. Now imagine a second reader comes along and also had R v3.4.3 but had neither the ggplot2 nor the cowplot package installed. They also read the chapter in April, but they install both packages in April, so they get the latest version of both packages available in April for R v3.4.3. Even though both you and the other reader had the same version of R installed, you will end up with different package versions from each other, and likely different versions yet from whatever versions we used to write the book. The end result is that different people, even with the same version of R, very likely are using different versions of different packages. This can pose a major challenge for reproducibility. If you are reading a book, it can be a frustration because code does not seem to work as we said it would. If you are using code in production or for scientific research or decision-making, nonreproducibility can pose an even bigger challenge. The solution to standardize versions across people and ensure results are fully reproducible is to control not only the version of R but also the version of all packages. This requires a different approach to package installation and management than the default system, which uses the latest package versions from CRAN. The checkpoint package is designed to solve this challenge. It does require some extra steps and processes to use, and at first may seem a nuisance, but the payoff is that you can be guaranteed that you are not only using the same version of R but also the same version of all packages. To understand how the checkpoint package works, we need a bit more background regarding how R’s libraries and package system work. Mainstream R packages are distributed through CRAN. Package authors can submit new versions of their packages to CRAN, and CRAN updates nightly. For some operating xvi

Introduction

systems, CRAN just stores the package source code, such as for Linux machines. For others, such as Windows operating systems, CRAN builds precompiled package binaries and hosts those. CRAN keeps old source code but generally not old binary packages for long. On a local machine, when install.packages is run, R goes online to a repository, by default CRAN, finds the package name, downloads it, and installs it into a local library. The local library is basically just a directory on your own machine. R has a default location it likes to use as its local library, and by default when you install packages, they are added to the default library. Once a package is installed, when it is loaded or opened using library(), R goes to its default library, finds a package with the same name, and opens it. The checkpoint package works by creating a new library on the local machine, for a particular version of R for a particular date. Then it scans all the R script files in R’s current working directory—you can identify this using the getwd() function—and identifies any calls to the library() or require() functions. Then it goes and checks whether those packages are installed in the local library. If they are not, it goes to a snapshot of CRAN taken by another server setup to support the checkpoint package. That way, checkpoint can install the version of the package available from a specific date. In that way, the checkpoint package can ensure that you have the same specific version of R and specific version of all packages that we used when writing the book. Or if you are trying to re-run some analysis from a year ago, you can get the same version of those packages on a new computer. Assuming that you have the following code in an R script, you can use the checkpoint package to read the R script and find the call to library(data.table), and it will install the data.table package, which is a great package for data management [29]. If you do not want checkpoint to look in the current working directory, you can specify the project path, as we do to the book in this example. You can also change where checkpoint sets its library to another folder location, instead of the default location, which we also do. We accomplish both of these using variables set as part of our R project, book_directory and checkpoint_directory. If you are using checkpoint on your own machine, set those variables to the relevant directories, for example, as b­ ook_ directory