Beginning R 4: From Beginner to Pro [1 ed.] 148426052X, 9781484260524

https://www.apress.com/gp/book/9781484260524 Learn how to use R 4, write and save R scripts, read in and write out data

813 172 10MB

English Pages 467 [481] Year 2020

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Beginning R 4: From Beginner to Pro [1 ed.]
 148426052X, 9781484260524

Table of contents :
Table of Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Foreword
Chapter 1: Installing R
1.1 Your Tech Stack
1.2 Updating Your Operating System
Windows
MacOS
1.3 Downloading and Installing R from CRAN
Windows
MacOS
1.4 Downloading and Installing RStudio
Windows
MacOS
1.5 Using RStudio
New Projects
1.6 My First R Script
1.7 Summary
1.8 Practice for Mastery
Comprehension Checks
Exercises
Chapter 2: Installing Packages and Using Libraries
2.1 Installing Packages
haven
readxl
writexl
data.table
extraoperators
JWileymisc
ggplot2
visreg
emmeans
ez
palmerpenguins
2.2 Using Packages
2.3 Summary
2.4 Practice for Mastery
Comprehension Checks
Exercises
Chapter 3: Data Input and Output
3.1 Setup
3.2 Input
Manual Entry
CSV: .csv
Excel: .xlsx or .xls
RDS: .rds
Other Proprietary Formats
SPSS: .sav
Stata: .dta
SAS: .sas7bdat
3.3 Output
CSV
Excel
RDS
3.4 Summary
3.5 Practice for Mastery
Comprehension Checks
Exercises
Chapter 4: Working with Data
4.1 Setup
4.2 What Do Our Data Look Like?
4.3 How Does data.table Work?
How Do Row Operations Work?
order()
Subsetting
How Do Column Operations Work?
Choosing Columns
Creating Columns
How Do by Operations Work?
4.4 Examples
Example 1: Metropolitan Area Counts
Example 2: Metropolitan Statistical Areas (MSAs)
Example 3
4.5 Summary
4.6 Practice for Mastery
Comprehension Checks
Exercises
Chapter 5: Data and Samples
5.1 R Setup
5.2 Populations and Samples
5.3 Variables and Data
Example
Note
Example
Example
Thoughts on Variables and Data
5.4 Thinking Statistically
5.5 Evaluating Studies
5.6 Evaluating Samples
Convenience Samples
Example
Example
Kth Samples
Example
Example
Cluster Samples
Example
Example
Stratified Samples
Example
Example
Random Samples
Example
Example
Sample Recap
5.7 Frequency Tables
Example
Example
Example
5.8 Summary
5.9 Practice for Mastery
Comprehension Checks
Exercises
Chapter 6: Descriptive Statistics
6.1 R Setup
6.2 Visualization
Histograms
Example
Example
Dot Plots/Charts
Example
ggplot2
Example
Example
6.3 Central Tendency
Arithmetic Mean
Example
Example
Median
Example
Example
6.4 Position
Example
Example
Example
6.5 Turbulence
Example
Example
6.6 Summary
6.7 Practice for Mastery
Comprehension Checks
Exercises
Chapter 7: Understanding Probability and Distributions
7.1 R Setup
7.2 Probability
Example: Independent
Example: Complement
Probability Final Thoughts
7.3 Normal Distribution
Example
Example
Example
Example
7.4 Distribution Probability
Example
Example
7.5 Central Limit Theorem
Example
Example
Example
7.6 Summary
7.7 Practice for Mastery
Comprehension Checks
Exercises
Chapter 8: Correlation and Regression
8.1 R Setup
8.2 Correlations
Parametric
Example
Example
Example
Non-parametric: Spearman
Example
Example
Non-parametric: Kendall
Example
Example
Correlation Choices
8.3 Simple Linear Regression
Introduction
Assumptions
Linearity
Normality
Homoscedasticity
Independence
Linear Regression Assumption Summary
R2: Variance Explained
Linear Regression in R
Example
Example
8.4 Summary
8.5 Practice for Mastery
Comprehension Checks
Exercises
Chapter 9: Confidence Intervals
9.1 R Setup
9.2 Visualizing Confidence Intervals
Example: Sigma Known
Example: Sigma Unknown
Example
Example
9.3 Understanding Similar vs. Dissimilar Data
Example
Example
9.4 Summary
9.5 Practice for Mastery
Comprehension Checks
Exercises
Chapter 10: Hypothesis Testing
10.1 R Setup
10.2 H0 vs. H1
Example
Example
10.3 Type I/II Errors
Example
Example
Example
10.4 Alpha and Beta
10.5 Assumptions
10.6 Null Hypothesis Significance Testing (NHST)
Example
Example
Example
10.7 Summary
10.8 Practice for Mastery
Comprehension Checks
Exercises
Chapter 11: Multiple Regression
11.1 R Setup
11.2 Linear Regression Redux
Example
11.3 Multiple Regression
Implications of Multiple Predictors
Multiple Regression in R
Example
Effect Sizes and Formatting
Example
Example
Assumption and Cleaning
Example
Example
11.4 Categorical Predictors
Example
Example
11.5 Summary
11.6 Practice for Mastery
Comprehension Checks
Exercises
Chapter 12: Moderated Regression
12.1 R Setup
12.2 Moderation Theory
Moderation in R
12.3 Continuous x Categorical Moderation in R
Example
12.4 Continuous x Continuous Moderation in R
12.5 Summary
12.6 Practice for Mastery
Comprehension Checks
Exercises
Chapter 13: Analysis of Variance
13.1 R Setup
13.2 ANOVA Background
Formal Mathematics
13.3 One-Way ANOVA
Example
Example
13.4 Factorial ANOVA
Example
Example
13.5 Summary
13.6 Practice for Mastery
Comprehension Checks
Exercises
Bibliography
Index

Citation preview

Beginning R 4 From Beginner to Pro — Matt Wiley Joshua F. Wiley

Beginning R 4 From Beginner to Pro

Matt Wiley Joshua F. Wiley

Beginning R 4: From Beginner to Pro Matt Wiley Victoria College, Victoria, TX, USA ISBN-13 (pbk): 978-1-4842-6052-4    https://doi.org/10.1007/978-1-4842-6053-1

Joshua F. Wiley Turner Institute for Brain and Mental Health, Monash University, Melbourne, Australia ISBN-13 (electronic): 978-1-4842-6053-1

Copyright © 2020 by Matt Wiley, 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 by Shutterstock Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004, U.S.A. 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 e-mail [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/9781484260524. For more detailed information, please visit http://www.apress.com/source-code. Printed on acid-free paper

Table of Contents About the Authors�������������������������������������������������������������������������������������������������� xiii About the Technical Reviewer���������������������������������������������������������������������������������xv Acknowledgments�������������������������������������������������������������������������������������������������xvii Foreword����������������������������������������������������������������������������������������������������������������xix Chapter 1: Installing R���������������������������������������������������������������������������������������������� 1 1.1 Your Tech Stack����������������������������������������������������������������������������������������������������������������������� 2 1.2 Updating Your Operating System�������������������������������������������������������������������������������������������� 2 Windows���������������������������������������������������������������������������������������������������������������������������������� 2 MacOS������������������������������������������������������������������������������������������������������������������������������������� 3 1.3 Downloading and Installing R from CRAN������������������������������������������������������������������������������� 3 Windows���������������������������������������������������������������������������������������������������������������������������������� 3 MacOS������������������������������������������������������������������������������������������������������������������������������������� 4 1.4 Downloading and Installing RStudio��������������������������������������������������������������������������������������� 5 Windows���������������������������������������������������������������������������������������������������������������������������������� 6 MacOS������������������������������������������������������������������������������������������������������������������������������������� 6 1.5 Using RStudio�������������������������������������������������������������������������������������������������������������������������� 6 New Projects������������������������������������������������������������������������������������������������������������������������� 11 1.6 My First R Script������������������������������������������������������������������������������������������������������������������� 13 1.7 Summary������������������������������������������������������������������������������������������������������������������������������ 17 1.8 Practice for Mastery�������������������������������������������������������������������������������������������������������������� 18 Comprehension Checks��������������������������������������������������������������������������������������������������������� 18 Exercises������������������������������������������������������������������������������������������������������������������������������� 19

iii

Table of Contents

Chapter 2: Installing Packages and Using Libraries����������������������������������������������� 21 2.1 Installing Packages��������������������������������������������������������������������������������������������������������������� 23 haven������������������������������������������������������������������������������������������������������������������������������������� 24 readxl������������������������������������������������������������������������������������������������������������������������������������� 25 writexl������������������������������������������������������������������������������������������������������������������������������������ 25 data.table������������������������������������������������������������������������������������������������������������������������������ 26 extraoperators����������������������������������������������������������������������������������������������������������������������� 26 JWileymisc���������������������������������������������������������������������������������������������������������������������������� 27 ggplot2���������������������������������������������������������������������������������������������������������������������������������� 27 visreg������������������������������������������������������������������������������������������������������������������������������������� 28 emmeans������������������������������������������������������������������������������������������������������������������������������� 28 ez������������������������������������������������������������������������������������������������������������������������������������������� 29 palmerpenguins��������������������������������������������������������������������������������������������������������������������� 29 2.2 Using Packages��������������������������������������������������������������������������������������������������������������������� 29 2.3 Summary������������������������������������������������������������������������������������������������������������������������������ 30 2.4 Practice for Mastery�������������������������������������������������������������������������������������������������������������� 31 Comprehension Checks��������������������������������������������������������������������������������������������������������� 31 Exercises������������������������������������������������������������������������������������������������������������������������������� 31

Chapter 3: Data Input and Output��������������������������������������������������������������������������� 33 3.1 Setup������������������������������������������������������������������������������������������������������������������������������������� 33 3.2 Input�������������������������������������������������������������������������������������������������������������������������������������� 34 Manual Entry������������������������������������������������������������������������������������������������������������������������� 35 CSV: .csv�������������������������������������������������������������������������������������������������������������������������������� 36 Excel: .xlsx or .xls������������������������������������������������������������������������������������������������������������������ 38 RDS: .rds�������������������������������������������������������������������������������������������������������������������������������� 40 Other Proprietary Formats����������������������������������������������������������������������������������������������������� 41 3.3 Output����������������������������������������������������������������������������������������������������������������������������������� 43 CSV���������������������������������������������������������������������������������������������������������������������������������������� 43 Excel�������������������������������������������������������������������������������������������������������������������������������������� 44 RDS���������������������������������������������������������������������������������������������������������������������������������������� 44 iv

Table of Contents

3.4 Summary������������������������������������������������������������������������������������������������������������������������������ 44 3.5 Practice for Mastery�������������������������������������������������������������������������������������������������������������� 45 Comprehension Checks��������������������������������������������������������������������������������������������������������� 45 Exercises������������������������������������������������������������������������������������������������������������������������������� 46

Chapter 4: Working with Data�������������������������������������������������������������������������������� 47 4.1 Setup������������������������������������������������������������������������������������������������������������������������������������� 47 4.2 What Do Our Data Look Like?����������������������������������������������������������������������������������������������� 49 4.3 How Does data.table Work?��������������������������������������������������������������������������������������������� 52 How Do Row Operations Work?��������������������������������������������������������������������������������������������� 53 How Do Column Operations Work?���������������������������������������������������������������������������������������� 65 How Do by Operations Work?������������������������������������������������������������������������������������������������ 72 4.4 Examples������������������������������������������������������������������������������������������������������������������������������ 74 Example 1: Metropolitan Area Counts������������������������������������������������������������������������������������ 74 Example 2: Metropolitan Statistical Areas (MSAs)����������������������������������������������������������������� 76 Example 3������������������������������������������������������������������������������������������������������������������������������ 77 4.5 Summary������������������������������������������������������������������������������������������������������������������������������ 77 4.6 Practice for Mastery�������������������������������������������������������������������������������������������������������������� 79 Comprehension Checks��������������������������������������������������������������������������������������������������������� 79 Exercises������������������������������������������������������������������������������������������������������������������������������� 80

Chapter 5: Data and Samples��������������������������������������������������������������������������������� 81 5.1 R Setup��������������������������������������������������������������������������������������������������������������������������������� 82 5.2 Populations and Samples����������������������������������������������������������������������������������������������������� 82 5.3 Variables and Data���������������������������������������������������������������������������������������������������������������� 83 Example��������������������������������������������������������������������������������������������������������������������������������� 85 Example��������������������������������������������������������������������������������������������������������������������������������� 88 Example��������������������������������������������������������������������������������������������������������������������������������� 88 Thoughts on Variables and Data�������������������������������������������������������������������������������������������� 89 5.4 Thinking Statistically������������������������������������������������������������������������������������������������������������� 90

v

Table of Contents

5.5 Evaluating Studies���������������������������������������������������������������������������������������������������������������� 90 5.6 Evaluating Samples�������������������������������������������������������������������������������������������������������������� 92 Convenience Samples����������������������������������������������������������������������������������������������������������� 93 Kth Samples�������������������������������������������������������������������������������������������������������������������������� 95 Cluster Samples������������������������������������������������������������������������������������������������������������������ 100 Stratified Samples��������������������������������������������������������������������������������������������������������������� 103 Random Samples���������������������������������������������������������������������������������������������������������������� 107 Sample Recap��������������������������������������������������������������������������������������������������������������������� 110 5.7 Frequency Tables���������������������������������������������������������������������������������������������������������������� 112 Example������������������������������������������������������������������������������������������������������������������������������� 112 5.8 Summary���������������������������������������������������������������������������������������������������������������������������� 120 5.9 Practice for Mastery������������������������������������������������������������������������������������������������������������ 122 Comprehension Checks������������������������������������������������������������������������������������������������������� 122 Exercises����������������������������������������������������������������������������������������������������������������������������� 123

Chapter 6: Descriptive Statistics�������������������������������������������������������������������������� 125 6.1 R Setup������������������������������������������������������������������������������������������������������������������������������� 125 6.2 Visualization������������������������������������������������������������������������������������������������������������������������ 126 Histograms�������������������������������������������������������������������������������������������������������������������������� 127 Dot Plots/Charts������������������������������������������������������������������������������������������������������������������� 133 ggplot2�������������������������������������������������������������������������������������������������������������������������������� 135 6.3 Central Tendency����������������������������������������������������������������������������������������������������������������� 144 Arithmetic Mean������������������������������������������������������������������������������������������������������������������ 145 Median��������������������������������������������������������������������������������������������������������������������������������� 149 6.4 Position������������������������������������������������������������������������������������������������������������������������������� 153 Example������������������������������������������������������������������������������������������������������������������������������� 154 Example������������������������������������������������������������������������������������������������������������������������������� 157 Example������������������������������������������������������������������������������������������������������������������������������� 160

vi

Table of Contents

6.5 Turbulence�������������������������������������������������������������������������������������������������������������������������� 161 Example������������������������������������������������������������������������������������������������������������������������������� 166 Example������������������������������������������������������������������������������������������������������������������������������� 168 6.6 Summary���������������������������������������������������������������������������������������������������������������������������� 170 6.7 Practice for Mastery������������������������������������������������������������������������������������������������������������ 171 Comprehension Checks������������������������������������������������������������������������������������������������������� 172 Exercises����������������������������������������������������������������������������������������������������������������������������� 172

Chapter 7: Understanding Probability and Distributions�������������������������������������� 175 7.1 R Setup������������������������������������������������������������������������������������������������������������������������������� 176 7.2 Probability��������������������������������������������������������������������������������������������������������������������������� 177 Example: Independent��������������������������������������������������������������������������������������������������������� 179 Example: Complement��������������������������������������������������������������������������������������������������������� 181 Probability Final Thoughts��������������������������������������������������������������������������������������������������� 182 7.3 Normal Distribution������������������������������������������������������������������������������������������������������������� 183 Example������������������������������������������������������������������������������������������������������������������������������� 186 Example������������������������������������������������������������������������������������������������������������������������������� 188 Example������������������������������������������������������������������������������������������������������������������������������� 190 Example������������������������������������������������������������������������������������������������������������������������������� 192 7.4 Distribution Probability������������������������������������������������������������������������������������������������������� 197 Example������������������������������������������������������������������������������������������������������������������������������� 201 Example������������������������������������������������������������������������������������������������������������������������������� 203 7.5 Central Limit Theorem��������������������������������������������������������������������������������������������������������� 204 Example������������������������������������������������������������������������������������������������������������������������������� 207 Example������������������������������������������������������������������������������������������������������������������������������� 212 Example������������������������������������������������������������������������������������������������������������������������������� 217 7.6 Summary���������������������������������������������������������������������������������������������������������������������������� 220 7.7 Practice for Mastery������������������������������������������������������������������������������������������������������������ 222 Comprehension Checks������������������������������������������������������������������������������������������������������� 222 Exercises����������������������������������������������������������������������������������������������������������������������������� 222

vii

Table of Contents

Chapter 8: Correlation and Regression����������������������������������������������������������������� 225 8.1 R Setup������������������������������������������������������������������������������������������������������������������������������� 226 8.2 Correlations������������������������������������������������������������������������������������������������������������������������� 227 Parametric��������������������������������������������������������������������������������������������������������������������������� 230 Non-parametric: Spearman������������������������������������������������������������������������������������������������� 233 Non-parametric: Kendall����������������������������������������������������������������������������������������������������� 234 Correlation Choices������������������������������������������������������������������������������������������������������������� 237 8.3 Simple Linear Regression��������������������������������������������������������������������������������������������������� 238 Introduction������������������������������������������������������������������������������������������������������������������������� 238 Assumptions������������������������������������������������������������������������������������������������������������������������ 243 R 2: Variance Explained��������������������������������������������������������������������������������������������������������� 250 Linear Regression in R��������������������������������������������������������������������������������������������������������� 250 8.4 Summary���������������������������������������������������������������������������������������������������������������������������� 262 8.5 Practice for Mastery������������������������������������������������������������������������������������������������������������ 263 Comprehension Checks������������������������������������������������������������������������������������������������������� 263 Exercises����������������������������������������������������������������������������������������������������������������������������� 264

Chapter 9: Confidence Intervals��������������������������������������������������������������������������� 265 9.1 R Setup������������������������������������������������������������������������������������������������������������������������������� 266 9.2 Visualizing Confidence Intervals����������������������������������������������������������������������������������������� 268 Example: Sigma Known������������������������������������������������������������������������������������������������������� 272 Example: Sigma Unknown��������������������������������������������������������������������������������������������������� 279 Example������������������������������������������������������������������������������������������������������������������������������� 282 Example������������������������������������������������������������������������������������������������������������������������������� 284 9.3 Understanding Similar vs. Dissimilar Data�������������������������������������������������������������������������� 287 Example������������������������������������������������������������������������������������������������������������������������������� 287 Example������������������������������������������������������������������������������������������������������������������������������� 288 9.4 Summary���������������������������������������������������������������������������������������������������������������������������� 290 9.5 Practice for Mastery������������������������������������������������������������������������������������������������������������ 291 Comprehension Checks������������������������������������������������������������������������������������������������������� 291 Exercises����������������������������������������������������������������������������������������������������������������������������� 292 viii

Table of Contents

Chapter 10: Hypothesis Testing���������������������������������������������������������������������������� 293 10.1 R Setup����������������������������������������������������������������������������������������������������������������������������� 294 10.2 H0 vs. H1��������������������������������������������������������������������������������������������������������������������������� 295 Example������������������������������������������������������������������������������������������������������������������������������� 296 Example������������������������������������������������������������������������������������������������������������������������������� 296 10.3 Type I/II Errors������������������������������������������������������������������������������������������������������������������� 297 Example������������������������������������������������������������������������������������������������������������������������������� 298 Example������������������������������������������������������������������������������������������������������������������������������� 299 Example������������������������������������������������������������������������������������������������������������������������������� 300 10.4 Alpha and Beta������������������������������������������������������������������������������������������������������������������ 300 10.5 Assumptions��������������������������������������������������������������������������������������������������������������������� 304 10.6 Null Hypothesis Significance Testing (NHST)�������������������������������������������������������������������� 304 Example������������������������������������������������������������������������������������������������������������������������������� 306 Example������������������������������������������������������������������������������������������������������������������������������� 309 Example������������������������������������������������������������������������������������������������������������������������������� 312 10.7 Summary�������������������������������������������������������������������������������������������������������������������������� 314 10.8 Practice for Mastery���������������������������������������������������������������������������������������������������������� 315 Comprehension Checks������������������������������������������������������������������������������������������������������� 315 Exercises����������������������������������������������������������������������������������������������������������������������������� 316

Chapter 11: Multiple Regression�������������������������������������������������������������������������� 317 11.1 R Setup����������������������������������������������������������������������������������������������������������������������������� 318 11.2 Linear Regression Redux�������������������������������������������������������������������������������������������������� 320 Example������������������������������������������������������������������������������������������������������������������������������� 322 11.3 Multiple Regression���������������������������������������������������������������������������������������������������������� 329 Implications of Multiple Predictors�������������������������������������������������������������������������������������� 330 Multiple Regression in R������������������������������������������������������������������������������������������������������ 332 Effect Sizes and Formatting������������������������������������������������������������������������������������������������ 343 Assumption and Cleaning���������������������������������������������������������������������������������������������������� 359

ix

11.4 Categorical Predictors������������������������������������������������������������������������������������������������������� 366 Example������������������������������������������������������������������������������������������������������������������������������� 370 Example������������������������������������������������������������������������������������������������������������������������������� 374 11.5 Summary�������������������������������������������������������������������������������������������������������������������������� 378 11.6 Practice for Mastery���������������������������������������������������������������������������������������������������������� 379 Comprehension Checks������������������������������������������������������������������������������������������������������� 380 Exercises����������������������������������������������������������������������������������������������������������������������������� 380

Chapter 12: Moderated Regression���������������������������������������������������������������������� 383 12.1 R Setup����������������������������������������������������������������������������������������������������������������������������� 383 12.2 Moderation Theory������������������������������������������������������������������������������������������������������������ 384 Moderation in R������������������������������������������������������������������������������������������������������������������� 386 12.3 Continuous x Categorical Moderation in R������������������������������������������������������������������������ 389 Example������������������������������������������������������������������������������������������������������������������������������� 389 12.4 Continuous x Continuous Moderation in R������������������������������������������������������������������������ 401 12.5 Summary�������������������������������������������������������������������������������������������������������������������������� 411 12.6 Practice for Mastery���������������������������������������������������������������������������������������������������������� 412 Comprehension Checks������������������������������������������������������������������������������������������������������� 412 Exercises����������������������������������������������������������������������������������������������������������������������������� 413

Chapter 13: Analysis of Variance�������������������������������������������������������������������������� 417 13.1 R Setup����������������������������������������������������������������������������������������������������������������������������� 417 13.2 ANOVA Background����������������������������������������������������������������������������������������������������������� 419 Formal Mathematics������������������������������������������������������������������������������������������������������������ 422 13.3 One-Way ANOVA���������������������������������������������������������������������������������������������������������������� 426 Example������������������������������������������������������������������������������������������������������������������������������� 426 Example������������������������������������������������������������������������������������������������������������������������������� 433 13.4 Factorial ANOVA���������������������������������������������������������������������������������������������������������������� 437 Example������������������������������������������������������������������������������������������������������������������������������� 437 Example������������������������������������������������������������������������������������������������������������������������������� 450

x

Table of Contents

13.5 Summary�������������������������������������������������������������������������������������������������������������������������� 456 13.6 Practice for Mastery���������������������������������������������������������������������������������������������������������� 457 Comprehension Checks������������������������������������������������������������������������������������������������������� 457 Exercises����������������������������������������������������������������������������������������������������������������������������� 457

Bibliography��������������������������������������������������������������������������������������������������������� 459 Index��������������������������������������������������������������������������������������������������������������������� 461

xi

About the Authors Matt Wiley leads institutional effectiveness, research, and assessment at Victoria College, facilitating strategic and unit planning, data-informed decision making, and state/regional/federal accountability. As a tenured, associate professor of mathematics, he won awards in both mathematics education (California) and student engagement (Texas). Matt holds degrees in computer science, business, and pure mathematics from the University of California and Texas A&M systems. Outside academia, he has co-authored three books about the popular R programming language and was managing partner of a statistical consultancy for almost a decade. His programming experience is with R, SQL, C++, Ruby, Fortran, and JavaScript. A programmer, a published author, a mathematician, and a transformational leader, Matt has always melded his passion for writing with his joy of logical problem solving and data science. From the boardroom to the classroom, he enjoys finding dynamic ways to partner with interdisciplinary and diverse teams to make complex ideas and projects understandable and solvable. Matt enjoys being found online via Twitter (@matt_math) or http://mattwiley.org/. Joshua F. Wiley is a lecturer in the Turner Institute for Brain and Mental Health 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 co-develops a number of R packages including varian, a package to conduct Bayesian scale-location structural equation models; MplusAutomation, a popular package that links R to the commercial xiii

About the Authors

Mplus software; extraoperators for faster logical operations; multilevelTools for diagnostics, effect sizes, and easy display of multilevel/mixed effects model results; and miscellaneous functions to explore data or speed up analysis in JWileymisc. Joshua enjoys being found online via Twitter (@WileyResearch) or http://joshuawiley.com/.  

xiv

About the Technical Reviewer Rachel Winkenwerder is an associate professor of mathematics at Victoria College and serves as assistant director of institutional effectiveness, research, and assessment. With extensive mathematical teaching experience in China and Texas for both secondary and tertiary education, Rachel understands the practical development of a contextualized curriculum. Her most recent work in higher education includes co-chairing her institution’s curriculum and instructional council, reviewing regional accreditation narratives, and leading academic assessment. Her proven classroom track record teaching statistical methods courses combines with her current work in the R programming language and her earned degrees in computer science, mathematics, and education.  

xv

Acknowledgments We would like to sincerely thank all our students through and across the years, who collectively taught us A Great Many Important Things.

xvii

Foreword This book was, in part, written to be rigorously suitable for a sole mathematics course for undergraduates for what may be called “core.” In that respect, it may be suited to fit into a statistical methods course (usually with either an elementary or introductory modifier at the front). Additionally, depending on how far through the last chapters one goes, it may also be suitable for an upper-division undergraduate course for the social sciences (e.g., psychology or sociology). Beyond these objectives, however, this book is meant to empower learners to physically experience statistical thinking through the hands-on use of the R programming language. While theory will not be ignored, techniques and theory will be first motivated through models, visuals, and an intuitive approach. The true objective is to share a language for communicating complex numerical facts in understandable terms. This practical application – sometimes called empirical and quantitative skills – is designed to enable students to critically think and explore increasingly complex data sets, successfully describe and summarize large quantities of information, and accurately analyze, model, and communicate results to both technical and lay audiences. To make this happen, this text has two distinct parts. Part 1 is designed to efficiently walk the reader step by step through installing and understanding the essential minimums of the R programming language’s computer environment. We will do our best to avoid “techno speak,” maintain an everyday language that jump-starts the reader as fast as possible through the initial stages, and move as smartly as possible to studying actual statistics. Part 2 is a methods approach to introductory statistics. Populations, samples, descriptive statistics, probability, distributions, correlation, regression, confidence intervals, hypothesis testing, and analysis of variance (ANOVA) are all treated in turn. While not shying away from technical mathematical theory, all statistical ideas are first introduced conceptually. From visualizations to hands-on activities to help “get your hands dirty,” the goal is to build a solid, real-world, contextual intuition that makes the theory more relatable. Your authors’ goal is to help learners “live a statistical life” – and completely avoid writing a book used to pass one course and then quickly forgotten.

xix

Foreword

Lastly, while we have said this text is suitable for an undergraduate course, it will without a doubt increase a learner’s ability to use a highly popular programming language and lay the foundation for using R for research, data science, machine learning, dynamic reporting, and bespoke visualizations. As such, it is also suitable for practiced data analysts looking to make the transition to R, for graduate students looking to both gain a powerful skill and refresh their knowledge of statistics, and for anyone who enjoys learning about data and statistics. Thank you for spending your time and attention on our book. Please be sure to download source code and engage with this learning hands-on, and do not hesitate to reach out to us should anything not be working.

xx

CHAPTER 1

Installing R You are here to learn statistics, and the first step is installing some program. It can almost feel like a magician’s trick. You need to know some applied statistics, and somehow you need to learn how to program instead. While this can look scary, never fear! This chapter will walk you through step by step what you need to do to have a pain-free installation. Regardless of whether you are learning on your personal computer (be that a PC or Mac) or on your company/institution’s networked machine, this guide will let you know in everyday language what to do and yet stay complete enough to give to your IT department if needed (for corporate/institutional learners). It is worth mentioning that by learning how to think statistically using the R [16] language, you not only learn on free, open source software, you also start using statistics from day 1 the way it is used in “real” life. In addition to statistical knowledge, you gain some quite useful applied skills. This chapter helps you learn to be able to •

Download the latest version of R from CRAN [2] and install on either a Windows or Mac computer.



Download and install RStudio on either a Windows or Mac computer.



Understand the RStudio project environment.



Evaluate if your installations and understanding work through applying some basic R code principles.

If you already know something about R and are eager to get into learning statistics, we start by listing the software required for this book to work in Table 1-1. On the other hand, if you wish to journey through the walk with us, please proceed through the chapter.

© Matt Wiley, Joshua F. Wiley 2020 M. Wiley and J. F. Wiley, Beginning R 4, https://doi.org/10.1007/978-1-4842-6053-1_1

1

Chapter 1

Installing R

Table 1-1.  Beginning R Tech Stack Software

URL

R 4.0.2

https://cran.r-project.org/

RStudio 1.2.x

https://rstudio.com/products/rstudio/download/

Windows 10

www.microsoft.com/

MacOS

www.apple.com/macos

1.1  Your Tech Stack Because the software in Table 1-1 tend to all require each other in a certain order and are technologies, the list of software required for a project to work/run is sometimes referred to as a Tech Stack. If you find yourself having trouble installing R, one of the first things you would want to share with anyone helping you is your Tech Stack. In particular, your computer’s operating system will make a difference as may the version of R you are running. While this book is written for R.Version()[["version.string"]], most likely future versions will not change so very much that this book will not work.

1.2  Updating Your Operating System While it is not an absolute requirement, your computer’s operating system (e.g., Windows or macOS) should be up to date. An up-to-date operating system helps for a few reasons. Firstly, we are going to walk you through installing the latest version of R and RStudio. Those are for sure tested on the current operating system versions. Secondly, most “tech” types tend to keep their software updated; thus, it helps to have a system similar to what they are currently familiar with should you run into trouble.

W  indows To ensure Windows 10 is up to date is not difficult at all. In the operating system search bar (a magnifying glass most often to the right of the Windows logo), type check for updates and select the option titled Check for updates System settings with your mouse cursor. This should open Windows Update, and there will be a box titled Check for updates to click. If successful, the Last checked: Today text will include the current time. 2

Chapter 1

Installing R

Before you move on to actually installing R, now is a good time to verify your computer is a 64-bit machine. It is possible, although not as likely these days, that you may have a 32-bit computer. In that same Type here to search Windows search box, go ahead and type About your PC. This should bring up an option titled About your PC System settings. Selecting that will open up a screen with some information about your system. In particular, under Device specifications, you’re looking to see if your System type is either 64-bit or 32-bit. In either case, keep that in mind later on when you install R.

M  acOS Getting R running on macOS requires ensuring you have the latest version of macOS. This is important as the installation process differs across versions. At the time of writing, the latest version is macOS Catalina, with macOS Big Sur or later likely to be released by the time you are reading this. You can get help with upgrading from Apple: www.apple.com/au/macos/how-to-upgrade/.

1.3  Downloading and Installing R from CRAN With your operating system up to date, it is time to download the latest version of R. As of this writing, it is R version 4.0.2 (2020-06-22) and can be found at https://cran.r-­ project.org/. Depending on your operating system, you will install a slightly different version of R. Thus, we ask you choose your own adventure.

W  indows To install R on Windows 10, use your favorite web browser (e.g., Chrome, Firefox, or Edge) to visit https://cran.r-project.org/. There should be a box on that web page titled Download and Install R, and you will want to select the Download R for Windows link https://cran.r-project.org/bin/windows/. From there, your goal is to install base R, so go ahead and select the base link https://cran.r-project.org/bin/ windows/base/. The first link at the top should be Download R 4.0.2 for Windows (XX megabytes, 32/64 bit). It is both likely and possible that by the time you read this book, the version will be a larger number than 4.0.2. The megabytes may also likely be slightly different. Go ahead and download that latest version. Most likely, as long as the major version is still 4.x.x, everything in this book should stay fully or almost fully true. 3

Chapter 1

Installing R

After downloading, go ahead and navigate to your Downloads folder where the file R-4.0.2-win.exe is saved. Most often, your web browser will have a pop-up reminding you where the file is. Otherwise, you may press and hold the windows key on your keyboard followed by the E key which is sometimes called the Win + e. Not capital E, just the lowercase e key while still holding down the windows key button. This will open Windows Explorer, and most often there is a folder on the left titled Downloads. Once you have found your R-4.0.2-win.exe file, you will want to double-click it to start the install process. For now, go ahead and accept all the default options, clicking Next and OK as needed.

M  acOS To get R running most flexibly on macOS, several additional tools are suggested. Before you can install R, you need to install Xcode from App Store. After installation, open it to accept terms; otherwise, it may not work. Once you have Xcode installed, you also need to install command-line tools. Open Terminal (if you cannot find it, try spotlight search) and type in xcode-select --install and then press Enter to run. If you run into any access issues, you may need to enable root. You can do that by typing in Terminal the following: dsenableroot, and pressing Enter/Return to enable root user.

Note At the terminal, if you are asked to enter a password, type the password you use to log in to your Mac and press Enter/Return. When typing your password in the terminal, no characters will appear, but it is still being entered. Install XQuartz/X11. Visit www.xquartz.org/, download and run the file, and follow any on-screen instructions. Go to https://mac.r-project.org/tools/ and follow their instructions to get the mandatory tools and libraries. An example of the instructions includes, install gfortran by going to https://github.com/fxcoudert/gfortran-for-macOS/releases and download gfortran 8.2. Download and install following any instructions. Although not needed for R itself, for many add-on packages that extend R’s functionality, you will want some additional tools.

4

Chapter 1

Installing R

Install homebrew for macOS at https://brew.sh/ and follow the “Install Homebrew” steps. If you run into any access issues, you may need to enable root. You can do that by typing in Terminal the following: dsenableroot, and pressing Enter/Return to enable root user.

Note At the terminal, if you are asked to enter a password, type the password you use to log in to your Mac and press Enter/Return. When typing your password in the terminal, no characters will appear, but it is still being entered. Install openssl which allows R to securely download files and packages from the Internet. Do this by opening the terminal (you can search for “terminal” or look in the launchpad) and type this code once the terminal opens and press Enter: brew install openssl Install libgit2 which is needed for one of our graphing packages. Do this by opening the terminal (you can search for “terminal” or look in the launchpad) and type this code once the terminal opens and press Enter: brew install libgit2 Finally, download R by visiting https://cloud.r-project.org/ and clicking Download R for (Mac) OS X. Then download version 4.0.2. Once you have downloaded R, please be sure to install it to your apps.

1.4  Downloading and Installing RStudio Congratulations! You have now installed R. However, there is still one more thing to install. While R by itself is powerful, it is not a convenient working environment. In programming, one often works in something called an IDE (Integrated Development Environment). In our case, we want to install RStudio Desktop, which is going to add a lot of easy-to-use visuals to help us “see” R better. RStudio will make it easier to focus on learning statistics. Please visit https://rstudio.com/products/rstudio/download/ and select the RStudio Desktop Free option. As before, please catch up with us in the section that matches your operating system.

5

Chapter 1

Installing R

W  indows Having visited https://rstudio.com/products/rstudio/download/ and selected the RStudio Desktop Free option, you are now ready to install RStudio Desktop for Windows. As of this writing, the most up-to-date version is 1.3.1056.exe. Again as before, you will want to simply download the most recent version which should be step 2 on this website https://rstudio.com/products/rstudio/download/#download. Again, simply click the download button, and note where your browser is saving the file. To install, double-click the textttRStudio-1.3.1056.exe file. Also, as with R itself, you will want to go with all the default options as they are selected, clicking Next and OK as needed. Please note we are supposing you have a 64-bit operating system. If that is not the case, you will need one of the older copies of RStudio which may be found at this link: https://rstudio.com/products/rstudio/older-versions/.

M  acOS Having visited https://rstudio.com/products/rstudio/download/#download and selected the RStudio Desktop Free option, you are now ready to install RStudio Desktop for macOS. As of this writing, the most up-to-date version is 1.3.1056.dmg. Make sure R.app and RStudio.app are able to access disk resources needed. Follow this guide www.r-bloggers.com/escaping-the-macos-10-14-mojavefilesystem-sandbox-with-r-rstudio to give them the necessary permissions.

1.5  Using RStudio Now that you have R and RStudio installed, it is time to open and run RStudio for the first time. Go ahead and click the RStudio icon to open RStudio. What you should see is a small strip of icons along the top along with three large tiles or boxes that make up the bulk of the program screen. One large window pane on the left should be called Console, and inside that pane, there should be some text that reads R version 4.0.2 (or whatever the version of R you just downloaded and installed is).

6

Chapter 1

Installing R

On the right side, there should be two smaller window panes. On top is the Environment which should be empty. On the lower-right side should be the Files/Plots/ Packages/Help/Viewer pane. It should be showing you a file directory. Your first chore (and you will only do this once) is to set some default options to make sure we share the same settings. On the very top menu ribbon, find and click the Tools link, and then select Global Options from the drop-down menu. The Options menu should open, and you should be already in the General tab as in Figure 1-1. You will want to make sure the following options are not selected in that General tab ➤ Basic: •

Restore most recently opened project at startup: Not checked



Restore previously open source documents at startup: Not checked



Restore .RData into workspace at startup: Not checked



Save workspace to .RData on exit: Never

Go ahead and click Apply. Before you leave this Options menu, in order to have a little fun while you learn, please click Appearance as in Figure 1-2. Now, select the following options: •

RStudio theme: Modern.



Zoom: Set however you like.



Editor font: Choose your favorite font.



Editor font size: Big enough to read, small enough to optimize monitor space.



Editor theme: Vibrant Ink (we disagree on this – truly choose your favorite).

7

Chapter 1

Installing R

Figure 1-1.  RStudio general options

8

Chapter 1

Installing R

Figure 1-2.  RStudio Appearance

9

Chapter 1

Installing R

Figure 1-3.  RStudio Pane Layout

10

Chapter 1

Installing R

Figure 1-4.  RStudio New and Save example Lastly, please click Pane Layout and ensure your options match ours as in Figure 1-3. Now, at last, you are done with setup. Please click OK, and welcome to a world where we spend a great deal of time. Lastly, if you want to learn some more about using RStudio as an interface, the following two-page “cheat sheet” is a good place to go. It diagrams all the many parts of RStudio and how they can help you do your work: ­https://github.com/rstudio/ cheatsheets/raw/master/rstudio-ide.pdf.

N  ew Projects Now that RStudio has some good defaults, it is time to start your first project. Creating a project builds a folder that will hold your work, and it has some files unique to RStudio which will allow you to easily work on a related set of ideas. There is no right or wrong answer for how many R files should live in a project. If you are taking this book as part of a class, it may make sense to build one project for each chapter. In that case, a good project name would be the title of the chapter. On the other hand, this entire book was written in a single project titled “BeginningR_2020.” For now, let us go ahead and build one project for each chapter. At the very least, you will get comfortable starting, closing, and opening projects. 11

Chapter 1

Installing R

To start a new project, on the upper-left menu ribbon, select File and click New Project. You will want to then use the New Project wizard to choose New Directory ➤ New Project and then pick a Directory name. For now, we recommend 01Installing. Once that is typed into the Directory name field, select Create Project. You are now in your first project! Your first task is to create a new, blank R file. To do that, on the top ribbon, right under the word File, there is a small icon with a plus sign on top of a blank bit of paper. Click that icon, and then, from the menu of new files, pick the first one titled R Script. This blank file is now visible because you should have a tab in that top-left pane titled Untitled1. Go ahead and click the floppy disk–shaped save icon. Name this file MyFirstRScript.R and click Save. A screenshot showing what the new script and save look like is in Figure 1-4. If all has gone well, you now have four panes as we described earlier in the setup. Your top-left pane is titled MyFirstRScript.R and is a script or code pane. This is the area where we will do most of our work. Moving clockwise, your top-right pane is the Environment pane; it is still empty. The lower-right pane is your Files/Plots/Packages/ Help/Viewer pane. There should now be three files in your project directory which is in particular the Files tab. Those three files should be .Rhistory, 01Installing.Rproj, and MyFirstRScript.R. Lastly, on the lower left is your Console pane, and right now it should still be telling you about your current R version. That is all about to change. Let us briefly discuss the purpose of each of these panes in turn. The script pane, which currently holds your MyFirstRScript.R, is where you will type R code. Think of this just like a Word file or a PowerPoint slide. It will store and save any code you write there, and until you activate or run your code, nothing happens. If you like, this script area is your program. At present, your program is blank. We will change that very soon. You will write your first program in R, and become a programmer. The Environment pane shows the data or objects or variables your program has stored in memory. Right now, there is nothing there. Most commonly in this book, you will find some data in that spot. The Files tab shows your project’s working directory. Any files you want to use for this project need to live in this directory. This is important! R needs to know where to look for any Excel files or data files you use to get information for statistical analysis. Those files all need to live in the directory folder. However, this pane does more than just show you files. Notice there are tabs for Plots, Packages, Help, and Viewer. Go ahead and click through each of those in turn. For now, Plots and Files and Help will be your most common tabs here. Go ahead and get back to Files. 12

Chapter 1

Installing R

The last pane is the Console. This is where your code will run. There are two places code lives in RStudio. One is in the script area – that is where code is saved. However, to run code, it will always run in the console. With that, you have met the four areas that you will use to learn statistics. Before we are ready to wrap up this chapter, we want to make sure everything is working. It is time to write your first program.

1.6  My First R Script For a first program, we want to make sure R is working and hopefully see some interesting results. In this book, we are going to show you each bit of code, along with the output. When you follow along in your script, you will need to type out the code into your script area, use your mouse to click and drag to select the text (or hold Shift and use arrow keys on your keyboard to highlight the code) you want to run, and then press Ctrl+Enter to run the code on Windows or Cmd+Enter on macOS. Please note when we use the convention Ctrl+Enter, what we mean is to press and hold Ctrl and then press Enter and then let go of both keys. On macOS, it means press and hold the Cmd key and then press Enter/Return and then let go of both keys. This is the easiest way to run code from the script area. In the long term, it will save you a lot of time compared to using your mouse to click Run each time. In statistics, we are often in the business of trying to find a connection or a relationship between two parts of the same type of object. For example, we might imagine that as a vehicle’s weight increases, the miles per gallon (a measure of fuel efficiency) decreases. To see how we can use R to explore such a physical concept, let us take a brief look at our first data set. The data set mtcars is a car magazine dataset from quite some time ago. Go ahead and type mtcars into your script area, highlight that word, and press Ctrl+Enter. You should see the following 32 rows and 11 columns of data on your screen that are showing on our screens and showing here in this text. mtcars ##                     mpg cyl disp  hp drat  wt qsec vs am gear carb ## Mazda RX4            21   6  160 110  3.9 2.6   16  0  1    4    4 ## Mazda RX4 Wag        21   6  160 110  3.9 2.9   17  0  1    4    4 ## Datsun 710           23   4  108  93  3.8 2.3   19  1  1    4    1 13

Chapter 1

## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##

Installing R

Hornet 4 Drive       21   6  258 110  3.1 Hornet Sportabout    19   8  360 175  3.1 Valiant              18   6  225 105  2.8 Duster 360           14   8  360 245  3.2 Merc 240D            24   4  147  62  3.7 Merc 230             23   4  141  95  3.9 Merc 280             19   6  168 123  3.9 Merc 280C            18   6  168 123  3.9 Merc 450SE           16   8  276 180  3.1 Merc 450SL           17   8  276 180  3.1 Merc 450SLC          15   8  276 180  3.1 Cadillac Fleetwood   10   8  472 205  2.9 Lincoln Continental  10   8  460 215  3.0 Chrysler Imperial    15   8  440 230  3.2 Fiat 128             32   4   79  66  4.1 Honda Civic          30   4   76  52  4.9 Toyota Corolla       34   4   71  65  4.2 Toyota Corona        22   4  120  97  3.7 Dodge Challenger     16   8  318 150  2.8 AMC Javelin          15   8  304 150  3.1 Camaro Z28           13   8  350 245  3.7 Pontiac Firebird     19   8  400 175  3.1 Fiat X1-9            27   4   79  66  4.1 Porsche 914-2        26   4  120  91  4.4 Lotus Europa         30   4   95 113  3.8 Ford Pantera L       16   8  351 264  4.2 Ferrari Dino         20   6  145 175  3.6 Maserati Bora        15   8  301 335  3.5 Volvo 142E           21   4  121 109  4.1

3.2   19  1  0    3    1 3.4   17  0  0    3    2 3.5   20  1  0    3    1 3.6   16  0  0    3    4 3.2   20  1  0    4    2 3.1   23  1  0    4    2 3.4   18  1  0    4    4 3.4   19  1  0    4    4 4.1   17  0  0    3    3 3.7   18  0  0    3    3 3.8   18  0  0    3    3 5.2   18  0  0    3    4 5.4   18  0  0    3    4 5.3   17  0  0    3    4 2.2   19  1  1    4    1 1.6   19  1  1    4    2 1.8   20  1  1    4    1 2.5   20  1  0    3    1 3.5   17  0  0    3    2 3.4   17  0  0    3    2 3.8   15  0  0    3    4 3.8   17  0  0    3    2 1.9   19  1  1    4    1 2.1   17  0  1    5    2 1.5   17  1  1    5    2 3.2   14  0  1    5    4 2.8   16  0  1    5    6 3.6   15  0  1    5    8 2.8   19  1  1    4    2

This is a good example of what is sometimes called raw data. There is a lot of information about each car, and each bit of information is in a column. This is a great time to take a moment and appreciate the power of your computer. While we have asked you to spend most this chapter – and indeed the entire first part of this text – practicing R instead of learning statistics right away, the payoff is right here. Can you imagine typing all these numbers into a calculator?! 14

Chapter 1

Installing R

We do not want all these columns. In fact, we only want to talk about the relationship between weight (wt) and miles per gallon (mpg). To only look at one set of numbers at a time, in R, we can go into our data’s columns by using the $ operator. Go ahead and type mtcars$wt on one line, press Enter to move to the next line, type mtcars$mpg, highlight both lines, and then run them by pressing Ctrl+Enter (Cmd+Enter for macOS) again. Your results should be matching our results printed here: mtcars$wt ##  [1] 2.6 2.9 2.3 3.2 3.4 3.5 3.6 3.2 3.1 3.4 3.4 4.1 3.7 3.8 5.2 5.4 ## [17] 5.3 2.2 1.6 1.8 2.5 3.5 3.4 3.8 3.8 1.9 2.1 1.5 3.2 2.8 3.6 2.8 mtcars$mpg ##  [1] 21 21 23 21 19 18 14 24 23 19 18 16 17 15 10 10 15 32 30 34 22 16 ## [23] 15 13 19 27 26 30 16 20 15 21 From here on out, we will not mention typing into the script, highlighting, or pressing Ctrl+Enter (Cmd+Enter for macOS). Instead, we will simply discuss ideas, discuss how to turn those ideas into code, and then show you both the code and the output. If you get stuck and feel it is running code in R that is the likely holdup, there are some useful videos online. If you are a student in a class, having taught several thousand of our own students over the years, we encourage you to reach out to your professor or instructor. Especially if you are so unlucky as to have one of us as your instructor, for sure reach out! On the other hand, if that is not possible, go ahead and reach out to us. We do not mind at all, will do our best to answer, enjoy hearing from readers, and can be reached readily enough. Go ahead and take a look at our bios in the front of this book and do not be shy if you need help. Moving on, having seen both weight and miles per gallon, we are ready to take a look at these two data points visually. If this works, you will have written your first program to plot() and visualize these two data sets. You will have also confirmed that all systems are go with RStudio and R. To tell R we want to plot something, we use the function called plot(x, y). Functions take one or more inputs (in this case, weight and miles per gallon) and give us an output (in this case, a plot of those two number pairs). If you are familiar with x-axis and y-axis from algebra, you will know to expect a graph like the one you see in Figure 1-­5. Go ahead and copy the code precisely as you see here in your script pane, highlight it, 15

Chapter 1

Installing R

and run the code! Your graph will show up in your Plots pane, which up until now was your Files pane. Remember you can click back to Files anytime you want. Notice you can export your plot if you like. Now is a great moment to share your first plot with the world. In programming, these types of first steps are sometimes called “hello worlds” (because, back when we first learned to program, graphics and visuals were rare, so instead our first program literally printed “hello world” to the console – tough times!). More than just an old 1970s era dataset, you now can visually see any data set you can get into R. Pretty powerful stuff.

30 20 10

mtcars$mpg

plot(x = mtcars$wt, y = mtcars$mpg)

2

3

4

5

mtcars$wt

Figure 1-5.  Plot of mtcars weight and miles per gallon As you look at your graph, notice some features about this graph. As the x-axis of mtcars$wt increases, the y-axis of mtcars$mpg decreases. That is what we might expect to see happen; a car’s weight should drag down the fuel efficiency. If you run this code on your own system, you may notice that the figure looks a little different. For example, Figure 1-5 is wider than it is tall, but we can change the aspect ratio (how tall vs. how wide the figure is); and although it is the same data, it looks a bit different. To show you what we mean by that, here we make the same figure but now roughly equal height and width in Figure 1-6. plot(x = mtcars$wt, y = mtcars$mpg)

16

Installing R

25 20 10

15

mtcars$mpg

30

Chapter 1

2

3

4

5

mtcars$wt

Figure 1-6.  Plot of mtcars weight and miles per gallon with a different aspect ratio that is roughly equal height and width rather than much wider than tall In RStudio, you can move your mouse cursor to the edge between panels to where you see multidirectional arrows and then click and draw to resize and reshape the panels of RStudio. The figure will automatically update to the shape you make for it. As we get into Chapter 2, we will explore some fancier graphics. All the same, this is a good first start. Go ahead and click the save icon once more. From there, select File and then Close Project which is almost at the end of the file menu. Having closed out your project, you are ready to close RStudio by clicking the X on the top right of the screen. The next time you open RStudio, if you need to get back into your Chapter 1 project, you may select File, and either Recent Projects will have a link to your 01Installing project or you may use Open Project… to navigate to your project file.

1.7  Summary In this book, we will wrap up each chapter with a summary such as in Table 1-2 detailing in order of introduction specific facts which may be useful to quickly reference. In particular, these facts may serve as a useful guide for the tools which will help you solve the exercises.

17

Chapter 1

Installing R

Table 1-2.  Chapter Summary Idea

What It Means

R

A statistical programming language.

RStudio

An Integrated Development Environment or IDE for R.

CRAN

Comprehensive R Archive Network.

mtcars

A data set about cars we will use often.

$

One R command to access columns by name.

plot(x = , y = )

The function name to make an x-axis and y-axis plot.

1.8  Practice for Mastery Check your progress and grow through practice by working through some exercises. Comprehension checks ask critical thinking questions that may be best answered with a written or verbal response. Part of the art of statistics is successfully communicating results to your stakeholders or audience. Sometimes that audience is highly technical and other times very much not technical. Exercises are more direct applications of the concepts explored in the chapter.

C  omprehension Checks 1. We used the data set mtcars in the script pane of RStudio. What happens if you were to go to the Console pane of RStudio and, at the prompt ¿, type mtcars and press Enter? Compare/contrast this behavior to highlighting and running mtcars in your saved MyFirstRScript.R. 2. In MyFirstRScript.R, you ran plot(x = mtcarswt, y = mtcarsmpg) to get the graph in Figure 1-6. What happens if you run plot(mtcarswt, mtcarsmpg)? Can you run plot(mtcarswt, mtcarsmpg) in the Console pane instead? What does this suggest?

18

Chapter 1

Installing R

Exercises 1. You met the mtcars data and plotted weight and miles per gallon. Using the same plot() function, change the input to create a graph with miles per gallon on the horizontal x-axis and weight on the vertical y-axis. 2. There is another data set native to R named iris. Using the methods described in this chapter with mtcars, explore iris, view the data in the Sepal.Length and Petal.Length columns, and create a graph with Sepal.Length on the horizontal x-axis and Petal.Length on the y-axis.

19

CHAPTER 2

Installing Packages and Using Libraries You installed R and RStudio and are now familiar with them. Now it is time to discover another feature of R that will help you learn statistics. In Chapter 1, your first R script used the function plot(x = mtcars$wt, y = mtcars$mpg). Then, just like magic, a graph appeared in your lower-right plot pane – except it was not magic. Behind the scenes, you were secretly using the graphics [15] package. What is a package? When a programmer writes code meant to be used more than one time, they tend to give that code a name, and we call those names functions. An R package is usually one or more functions collected together to solve a common or similar task. By collecting those functions together in a package, the package can be shared with many people. Keep in mind R is free and used by many of the best researchers around the world. Each one has skills solving certain types of problems. By sharing their functions in packages, we all benefit together. This is exactly what happened when you used the plot() function. Some programmers (in this case, the R core programming team) got together and wrote in a script some functions to create graphs (including the plot function). They put all that code together in the graphics package. Using plot() did not take any extra work on your part, because some packages are so popular they are included in R by default. However, most packages are not included by default. Most packages are not needed by everyone; including them all would make downloading R take far too long. Instead, packages are kept on CRAN [2], ready to download at need. There is more to packages than what we said here. If you would like to learn more about packages (and perhaps write your own), please see Advanced R: Data Programming and the Cloud [23] for details.

© Matt Wiley, Joshua F. Wiley 2020 M. Wiley and J. F. Wiley, Beginning R 4, https://doi.org/10.1007/978-1-4842-6053-1_2

21

Chapter 2

Installing Packages and Using Libraries

By the end of this chapter, you should be able to •

Know packages are a way to add extra features to R.



Install add-on packages for R with the install.packages() function.



Activate packages for your R scripts by using the library() function.



Understand when to install a package from CRAN and when to use a local library.

If you already know about packages and are eager to get into learning statistics, go ahead and install these packages in Table 2-1 to move ahead to the next chapter. If you would like to follow along with us as we meet these packages you will use throughout this book, go ahead and continue through this chapter.

Table 2-1.  Package List Package

Use

haven [19]

Input and output common statistical file types from SPSS, Stata, and SAS.

readxl [18]

Input Microsoft .xlsx files to R.

writexl [14]

Output Microsoft .xlsx files from R.

data.table [9]

Efficiently and easily manage data/rows/columns.

extraoperators [20]

An R package with operators to help speed up everyday tasks.

JWileymisc [21]

An R package with aces_daily simulated data.

ggplot [17]

Customizable visualizations, graphics, plots for exploratory data analysis (EDA).

visreg [7]

Visualization of regression models.

emmeans [13]

Summarize statistical models.

ez [12]

Easy Analysis and Visualization of Factorial Experiments (we will use this for ANOVA).

palmerpenguins [11]

A fresh, fun data set about penguins (currently on GitHub).

22

Chapter 2

Installing Packages and Using Libraries

2.1  Installing Packages A package only needs to be installed once per computer. In other words, it should not be installed each time a new project is started. It can be difficult, when learning so many new things, to keep track of what to do when. So, provided you are learning R with us using a single computer, you should only need to install these packages once each. It also does not matter if you install a package while you are inside a project or whether you just install from the Console pane. Either way, it will be installed on your computer, and those features/functions will be available to you from any project you had, have, or will have, on that computer. That being said, of course if you go onto a new computer and want to run your script over there on that new machine, you will need to install the packages you use again on that new machine. Another thing to know about packages is they often depend on other packages. Thus, as you install each package, you may find that despite a plan to install just one package, in the Console pane you may see R is in fact installing several. This is all part of the natural process of package installation and nothing about which to worry. R is clever enough to know all the dependencies needed and will only install missing packages (thus, the order packages are installed can make a difference). To install a new package from CRAN, we use the install.packages(pkgs = "") function. R is a case-sensitive language, and CRAN enforces the rule that no package can have precisely the same name as another. However, one must be careful to spell a package exactly correctly; otherwise, the search feature of the install function will not work. Additionally, since R is case sensitive, one must match the upper- or lowercase letters perfectly as well. Thus, each of the following subsections will not follow standard capitalization rules. Rather, we choose to only use the package name in its fully correct form. As we go through the installation of each package, we also mention briefly just a little bit about how it is used and what additional features it adds to base R. Note that when you install a package, you may get a lot of output on the console. This can seem overwhelming, but it’s not anything you need to worry about. Generally if there is a problem, you will see something about an “error” or sometimes “non-zero exit status” which is a common way in technical worlds of meaning there was at least one, but maybe more, error or problem. Although it may seem confusing, it comes from the idea that “zero exit status” would mean zero issue by the time it exited the installation

23

Chapter 2

Installing Packages and Using Libraries

process. From that view, “non-zero exit status” means there are some errors or problems. If you do not have errors or “non-zero exit status,” there is a good chance that all the information and text shown as packages install is nothing to be concerned about. Finally, although we will make use of several different add-on packages, you do not need to know everything about these packages. That is, you do not need to study each package. We use sometimes just a few functions from a package to get what we need done as easily and efficiently as possible. It is perfectly okay to install a package to use one function and not learn about any of the other (possibly many) functions in that package.

h aven In the world of statistical computing, R is the increasingly popular newcomer. Because of R’s newcomer status, there are often times when importing data comes from some of the classical programs such as SPSS, Stata, or SAS. The haven package [19] provides functions to read data from these sources into R. Depending on your computer, and if your system has never installed R or any packages before, you may find that more than just the haven package is installed. This is because haven itself depends on some other packages. All the same, if, after you run install.packages(pkgs = "haven"), you see the last part of your output matches ours, then your first external package installation will be a success. We save practical applications of haven functions for Chapter 3 on data input and output. install.packages(pkgs = "haven") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'haven' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

24

Chapter 2

Installing Packages and Using Libraries

readxl Due to the popularity of the Microsoft Office software suite, Excel-style files are also common sources of data. Due to their popularity, it can be useful to input data from .xlsx files. The readxl package [18] allows this to happen. As before, you may have a handful of additional packages that R will automatically install for you as dependencies of readxl. Notice too that R functions can be somewhat clever about their input. In this case, we are using the fact that the install.packages() function is expecting the package name as the first input. Thus, we do not need to explicitly state pkgs = "readxl". Going forward, we will use a function’s formal input name for the first time we introduce a function. After the first use, we will only use the formal input name when required. install.packages("readxl") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'readxl' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

writexl In addition to reading Excel files, when communicating our results to others, it can be helpful to write Excel files too. The writexl package [14] allows us to write .xlsx files. install.packages("writexl") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'writexl' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

25

Chapter 2

Installing Packages and Using Libraries

data.table Once data are input to R, often we must work with the data for a bit prior to being able to perform statistical analytics. This can range from calculating summary tables to only grabbing out a subset of the total data available. In order to allow us to handle even large amounts of data with ease (not every data set is as short as mtcars), we use the data. table package [9] to allow us to manipulate or “munge” data. install.packages("data.table") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'data.table' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

extraoperators When working with larger data sets, it can be useful to study smaller subsets of information. While base R has the ability to readily chain together multiple criteria for such subsetting, it is not always clear to read such code. Additionally, such code can be long. The extraoperators package [20] saves keystrokes and makes various logical comparisons less convoluted. install.packages("extraoperators") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'extraoperators' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

26

Chapter 2

Installing Packages and Using Libraries

JWileymisc The JWileymisc package [21] has a simulated dataset (aces_daily) based on a 12-day study of research participants’ self-reported measures including stress and affect. The participants reported in three times per day, although, as usual for real-world research (or simulations thereof ), there may be missing data. This data set helps us understand statistical methods beyond the “classroom-perfect” examples more commonly seen. install.packages("JWileymisc") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'JWileymisc' successfully unpacked and MD5  sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

ggplot2 Your first program was a plot using the base graphics package. We often have need of more custom or more advanced graphics. Much like R is a statistical programming language, the ggplot2 package [17] uses what is called the grammar of graphics. install.packages("ggplot2") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'ggplot2' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

27

Chapter 2

Installing Packages and Using Libraries

visreg A common statistical method is taking data and finding some mathematical relationships between the inputs or predictors of a model and the output or the target. This allows researchers to understand the relationship between independent variables that can be controlled or adjusted and dependent variables. We saw a simple example of this with a predictor of car weight to an output or dependent variable of miles per gallon. The visreg package [7] makes it very easy to visualize parts of those models. It can be easier to understand statistical ideas with the right picture, and this package will both help you learn how a model works and how to communicate your results effectively. install.packages("visreg") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'visreg' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

emmeans The emmeans package [13] helps us summarize and get follow-up tests on statistical models to aid understanding and displaying results in a way that is easy to interpret. We will install this package now. install.packages("emmeans") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'emmeans' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

28

Chapter 2

Installing Packages and Using Libraries

ez Our penultimate package is the ez package [12] which helps us perform a statistical method called analysis of variance (ANOVA). We discuss ANOVA near the end of this book. All the same, we will install this package now. install.packages("ez") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'ez' successfully unpacked and MD5 sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

palmerpenguins Our last package gives us data rather than any statistical computations. The palmerpenguins package [11] includes a popular data set about penguins! install.packages("palmerpenguins") ## Installing package into 'C:/Users/.../R/win-library/4.0' ## (as 'lib' is unspecified) ## package 'palmerpenguins' successfully unpacked and MD5  sums checked ## ## The downloaded binary packages are in ##      C:\...\downloaded_packages

2.2  Using Packages Now that these packages have all been installed, it is time to make sure the installation worked. You may recall that packages only need to be installed once per computer. However, every time you are wanting to use a function from a package, you will have to let R know which packages to search. This is because when you use a function (remember a function is just a name for some specific code that does a specific task), 29

Chapter 2

Installing Packages and Using Libraries

R needs to match the function name you type to the code that does the work. Rather than waste time searching all the packages you may have installed (we have a couple hundred on our computers), we tell R which packages to search for a particular script by using the library() call. This needs to be run each time you start up one of your scripts in the script pane. Thus, convention says to put that call near the top of your code. This gives other users of your script a warning that, if they do not have one of those packages installed, they must install it before using your code. It is enough to run the library call once per session. Every time you start RStudio and open a project, you need to run any library calls. It is easy enough to run the calls, and, going forward, we start each chapter with any library calls needed for that chapter’s code. To show you what a successful call looks like, we go ahead and run the readxl package: library(readxl) As you can see, it is not especially exciting. If the package is already installed, a good library call usually does not display any text. However, sometimes, a successful library call may give you just a bit of information, as the data.table package does: library(data.table) ## data.table 1.13.0 using 6 threads (see ?getDTthreads). Latest news: r-datatable.com In contrast, trying to use a package that is not installed will result in an error: library(fake) ## Error in library(fake): there is no package called 'fake' You have now completed the installation of all the background software and packages needed for the rest of this book. Congratulations! From here on out, we will first learn some code together and then onward into full statistics.

2.3  Summary In this book, each chapter concludes with a summary such as in Table 2-2 detailing in order of introduction specific facts which may be useful to quickly reference. 30

Chapter 2

Installing Packages and Using Libraries

Table 2-2.  Chapter Summary Idea

What It Means

install.packages(pkgs = "")

Installs packages named; need only be run once per computer.

library()

Loads a package into memory for use in a script; need only be run once per session.

2.4  Practice for Mastery Check your progress and grow through practice by working through some exercises. Comprehension checks ask critical thinking questions that may be best answered with a written or verbal response. Part of the art of statistics is successfully communicating results to your stakeholders or audience. Sometimes that audience is highly technical and other times very much not technical. Exercises are more direct applications of the concepts explored in the chapter.

C  omprehension Checks 1. Suppose you share some R code you wrote with a friend. Would that friend need to install any packages your code used on their computer?

E xercises 1. Visit https://rdatatable.gitlab.io/data.table/ and download the data.table cheat sheet from the package author. 2. Using the search engine of your choice, search this phrase – R ggplot2 – and see if you can find a cheat sheet.

31

CHAPTER 3

Data Input and Output In general, when performing a statistical analysis, the majority of time spent ends up being dealing with data. This involves successfully inputting data as well as organizing or cleaning data. For now, our goal is to recognize various types of data files and use those types to import and export data to and from R. By the end of this chapter, you should be able to •

Recognize common data file types by suffix.



Apply R packages and functions to import data into R.



Apply R packages and functions to export data out of R.

3.1  Setup In order to practice inputting and outputting the various types of files you may use, we need to do some setup. In order to continue practicing creating and using projects, we will start a new project for this chapter. Inside that project, we also will create some folders and download some data files from this book’s GitHub site. If necessary, review the steps in Chapter 1 to create a new project. After starting RStudio, on the upper-left menu ribbon, select File and click New Project. Choose New Directory ➤ New Project, with Directory name 03DataIO, and select Create Project. To create an R script file, on the top ribbon, right under the word File, click the small icon with a plus sign on top of a blank bit of paper, and select the R Script menu option. Click the floppy disk–shaped save icon, name this file DataIO.R, and click Save. In the lower-right pane, you should see your project’s two files, and right under the Files tab, click the button titled New Folder. In the New Folder pop-up, type data and select OK. In the lower-right pane, click your new data folder. Repeat the folder creation process, making a new folder titled ch03.

© Matt Wiley, Joshua F. Wiley 2020 M. Wiley and J. F. Wiley, Beginning R 4, https://doi.org/10.1007/978-1-4842-6053-1_3

33

Chapter 3

Data Input and Output

Next, you need to download some files from this book’s site. They should live on GitHub at http://github.com/apress/beginning-r-4. However, the permanent link can also be found on the website http://mattwiley.org/publications.html by clicking Code for Beginning R. Navigate to this chapter’s folder and download the Texas counties data [3] as well as the American Community Survey [4] data into the ch03 folder you just created. In all, you should have six files in your project’s subfolders. With that set up, you are ready to practice importing and exporting data. If you need any refresher or quick tips on where to find things in RStudio as you go through the chapter, look at this short “cheat sheet” which has visuals and labels for most of RStudio’s features: https://github.com/rstudio/cheatsheets/raw/master/ rstudio-ide.pdf.

3.2  Input When inputting files to R, the usual way data arrive is in some sort of table format where there are named columns or variables and numbered rows or observations. Each column thus represents a category, and each row represents a specific measurement of those variables. The usual challenges to inputting these types of “mostly decent” data tend to be successfully reading the type of file storing the data and adapting to any unique aspects of different data files (such as the first few rows being of a different format than expected). An example of such a foible might be that a data gatherer/creator may include some notes or comments in the first few lines of an Excel file. It is only after these notes that the actual columns and rows of data start.

Note  When we say the type of file, we mean things like an Excel spreadsheet or a comma-separated text file or a dataset from another proprietary piece of software. Almost always, the type of a file is indicated by the extension. The file extension are the last few characters of the file name after the period. For example, an Excel file might be called “data.xlsx”. In this case, the file name is “data” and the extension is “.xlsx”; and the extension, the “.xlsx” part, is what tells us that it is an Excel file. Other common extensions are “.csv” which means a text file with cells separated by commas and “.rds” which is R’s own format for storing data. All of these can be told by looking at the file extension. 34

Chapter 3

Data Input and Output

Thus, our first task is to identify the correct function (and package) to read in our data as well as determine if we need to skip some rows. The majority of functions written to input data have at least three variables as options that include the location of the data file, the number of rows to skip, and whether the data has a header with column names. It is worth noting most data input functions generally default to assuming the first row is a column name header and no rows should be skipped. Most input functions include many options – and in general most of those do not need to be used. In fact, the easiest way to take care of some messiness in a file is often to open it yourself by hand, fix it manually, and then import into R. On the other hand, if you routinely get a file (perhaps some sort of daily update from some company or third party) and that file is predictable in the way it does not work nicely, it may be worth exploring additional function options to code an automatic read.

Manual Entry While we usually focus on input as something that involves some external file to read in, it is possible to input data by hand in R. This can be useful for several scenarios, including setting up some variables all the way to more extensive data input. In R, the assignment operator is