-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-intro-r.Rmd
214 lines (149 loc) · 8.65 KB
/
01-intro-r.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
---
editor_options:
markdown:
wrap: sentence
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
warning = FALSE,
message = FALSE) #Here, I have made it so that when you knit your .rmd, warnings and messages will not show up in the html markdown.
```
# Introduction to R and RStudio
------------------------------------------------------------------------
This walkthrough is presented by the IMMERSE team and will go through some common tasks carried out in R.
There are many free resources available to get started with R and RStudio.
One of our favorites is [*R for Data Science*](https://r4ds.had.co.nz/).
------------------------------------------------------------------------
- *R*[@rcore2017] is a free, open-source programming language and environment widely used for statistical computing, data analysis, and data visualization.
- *RStudio*[@rstudio2020] is an integrated development environment (IDE) for R, providing an intuitive interface that makes coding, visualization, and project management more accessible.
- *Mplus*[@muthen2017] is a statistical modeling program used for analyzing complex data, such as latent variable models, structural equation modeling, and growth modeling.
This book uses an R package called `MplusAutomation` to automate the process of running models, extracting results, and generating data visualizations.
------------------------------------------------------------------------
## Installation
------------------------------------------------------------------------
### Step 0: Install R, RStudio, and Mplus
[Here](https://posit.co/download/rstudio-desktop/) you will find a guide to installing both R and R Studio.
You can also install Mplus [here](https://www.statmodel.com/orderonline/).
*Note*: The installation of Mplus requires a paid license with the mixture add-on.
IMMERSE fellows will be given their own copy of Mplus for use during the one year training.
------------------------------------------------------------------------
## Set-up
------------------------------------------------------------------------
### Step 1: Create a new R-project in RStudio
R-projects help us organize our folders , filepaths, and scripts.
To create a new R project:
- File --\> New Project...
Click "New Directory" --\> New Project --\> Name your project
### Step 2: Create an R-markdown document
An R-markdown file provides an authoring framework for data science that allows us to organize our reports using texts and code chunks.
This document you are reading was made using R-markdown!
To create an R-markdown:
- File --\> New File --\> R Markdown...
In the window that pops up, give the R-markdown a title such as "**Introduction to R and RStudio**" Click "OK." You should see a new markdown with some example text and code chunks.
We want a clean document to start off with so delete everything from line 10 down.
Go ahead and save this document in your R Project folder.
### Step 3: Load packages
Your first code chunk in any given markdown should be the packages you will be using.
To insert a code chunk, etiher use the keyboard shortcut ctrl + alt + i or Code --\> Insert Chunk or click the green box with the letter C on it.
There are a few packages we want our markdown to read in:
```{r}
library(psych) # describe()
library(here) #helps with filepaths
library(gt) # create tables
library(tidyverse) #collection of R packages designed for data science
```
As a reminder, if a function does not work and you receive an error like this: `could not find function "random_function"`; or if you try to load a package and you receive an error like this: `` there is no package called `random_package` `` , then you will need to install the package using `install.packages("random_package")` in the console (the bottom-left window in R studio).
Once you have installed the package you will *never* need to install it again, however you must *always* load in the packages at the beginning of your R markdown using `library(random_package)`, as shown in this document.
The style of code and package we will be using is called [`tidyverse`](https://www.tidyverse.org/)[@wickham2019] .
Most functions are within the `tidyverse` package and if not, I've indicated the packages used in the code chunk above.
------------------------------------------------------------------------
## Explore the data
------------------------------------------------------------------------
### Step 4: Read in data
To demonstrate mixture modeling in the training program and online resource components of the IES grant we utilize the *Civil Rights Data Collection (CRDC)* (CRDC) data repository.
The CRDC is a federally mandated school-level data collection effort that occurs every other year.
This public data is currently available for selected latent class indicators across 4 years (2011, 2013, 2015, 2017) and all US states.
In this example, we use the Arizona state sample.
We utilize six focal indicators which constitute the latent class model in our example; three variables which report on harassment/bullying in schools based on disability, race, or sex, and three variables on full-time equivalent school staff hires (counselor, psychologist, law enforcement).
This data source also includes covariates on a variety of subjects and distal outcomes reported in 2018 such as math/reading assessments and graduation rates.
```{r, echo=FALSE, eval=TRUE}
tribble(
~"Name", ~"Label", ~"Values",
#--------------|--------------------------------|-----|,
"leaid", "District Identification Code", "",
"ncessch", "School Identification Code", "",
"report_dis", "Number of students harassed or bullied on the basis of disability", "0 = No reported incidents, 1 = At least one reported incident",
"report_race", "Number of students harassed or bullied on the basis of race, color, or national origin", "0 = No reported incidents, 1 = At least one reported incident",
"report_sex", "Number of students harassed or bullied on the basis of sex", "0 = No reported incidents, 1 = At least one reported incident",
"counselors_fte", "Number of full time equivalent counselors hired as school staff", "0 = No staff present, 1 = At least one staff present",
"report_sex", "Number of full time equivalent psychologists hired as school staff", "0 = No staff present, 1 = At least one staff present",
"counselors_fte", "Number of full time equivalent law enforcement officers hired as school staff", "0 = No staff present, 1 = At least one staff present") %>%
gt() %>%
tab_header(
title = "LCA indicators" # Add a title
) %>%
tab_options(
table.width = pct(75)
) %>%
tab_footnote(
footnote = "Civil Rights Data Collection (CRDC)",
location = cells_title())
#PDF Option:
#kableExtra::kable(df, caption = "LCA Indicators", booktabs = TRUE) %>%
# kableExtra::kable_styling(latex_options=c("striped","scale_down"))
```
**To read in data in R**:
```{r}
data <- read_csv(here("data", "crdc_lca_data.csv"))
```
**Ways to view data in R**:
1. click on the data in your Global Environment (upper right pane) or use...
```{r, eval = FALSE}
View(data)
```
2. `summary()` gives basic summary statistics & shows number of NA values (great for checking that data has been read in correctly)
```{r}
summary(data)
```
3. `names()` provides a list of column names. Very useful if you don't have them memorized!
```{r}
names(data)
```
4. head() prints the top 6 rows of the dataframe
```{r}
head(data)
```
### Step 5: Descriptive Statistics
Let's look at descriptive statistics for each variable.
Because looking at the ID variables' (`leaid`) and (`necessch`) descriptives is unnecessary, we use `select()` to remove the variable by using the minus (`-`) sign:
```{r}
data %>%
select(-leaid, -ncessch) %>%
summary()
```
Alternatively, we can use the `psych::describe()` function to give more information:
```{r}
data %>%
select(-leaid, -ncessch) %>%
describe()
```
What if we want to look at a subset of the data?
For example, what if we want to subset the data to observe a specific school district?
(`leaid`) We can use `tidyverse::filter()` to subset the data using certain criteria.
```{r}
data %>%
filter(leaid == "0408800") %>%
describe()
#You can use any operator to filter: >, <, ==, >=, etc.
```
Since we have binary data (0,1), it would be helpful to look at the proportions:
```{r}
data %>%
drop_na() %>%
pivot_longer(report_dis:law_fte, names_to = "variable") %>%
group_by(variable) %>%
summarise(prop = sum(value)/n(),
n = n()) %>%
arrange(desc(prop))
```
<div style="text-align: center;"><img src="images/ucsb_logo.png" width="75%" /></div>