-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript_template_specific.R
More file actions
287 lines (196 loc) · 7.69 KB
/
Copy pathscript_template_specific.R
File metadata and controls
287 lines (196 loc) · 7.69 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#### Analysis of <PROJECT NAME> ####
# In this study, <brief description of study>.
# <Important study details>.
# <Experimental design>.
# To run this script: open the R project in the main folder of this repository.
## Setup ---------------------------------------------------------------------------------------
# This section loads the required packages, reads in the data required for the analysis, and
# provides some simple summaries of the data structure.
## Load R environment --------------------------------------------------------------------------
# NB: the user needs to have Rtools installed to be able to download package versions
# that are only available as source files.
# Need to install packages?
install_needed <- TRUE
# Want to use renv to restore the versions of packages used in the original analysis?
use_renv <- TRUE
# Install packages and set up environment
if(install_needed) {
if(use_renv) {
renv::restore()
# NB: this only works well when the R version used is the same as recorded
# in the renv.lock file (here: v.4.5.2)
# if renv::restore() fails, restart R, turn USE_RENV to FALSE and try again
} else {
# when renv::restore() fails, delete the renv.lock file
file.remove("renv.lock")
# and create and record your own environment
renv::init()
renv::snapshot()
}
# Install any packages that renv misses
if(!require(<package1>)) renv::install("<package1>")
if(!require(<package2>)) renv::install("<package2>")
}
# Check that analysis environment was set up well
renv::status()
# NB: resolve any issues following renv instructions
# Setting seed to ensure random processes are reproducible
set.seed(<seed>)
## Load packages -------------------------------------------------------------------------------
library(tidyverse) # Used for data cleaning and manipulation (includes dplyr library)
library(performance) # Used to check model assumptions
library(testthat) # Used for unit tests
library(knitr) # Used to automatically turn script into .Rmarkdown file
library(rmarkdown) # Used to automatically turn .Rmd into HTML file
library(<package>) # <describe use of package in this script>
...
## User configuration --------------------------------------------------------------------------
# set to TRUE to save figures
save_figures <- TRUE
# set to TRUE to save tables
save_tables <- TRUE
# create output directory if saving is enabled
if(save_figures | save_tables) {
if(!dir.exists("output")) dir.create("output")
if(!dir.exists("output/result")) dir.create("output/result")
if(!dir.exists("output/fig")) dir.create("output/fig")
}
## Download data ------------------------------------------------------------------------------
# To run this script, the dataset '<filename>' needs to be downloaded from:
# <repository or DOI>
#
# The dataset should be saved in the folder data/
# Create folder to store the data
if(!dir.exists("data")) dir.create("data")
# Check if data is present in folder if not yet exists
file_name <- "<filename>"
file_path <- file.path("data", file_name)
# If not, want to automatically download it from the repository (does not require user input)?
download_data <- TRUE
if(download_data == TRUE & file.exists(file_path) == FALSE) {
# Specify doi of the repository and download
doi <- "<doi>"
tmp_files <- rdryad::dryad_download(doi)[[doi]]
# use deposits::deposit_download_file() for zenodo and figshare: https://github.com/ropenscilabs/deposits
# Copy desired file to data folder
file.copy(
tmp_files[grepl(file_name, tmp_files)],
"data",
overwrite = TRUE
)
}
# or manually place the data file in data/
## Load data -----------------------------------------------------------------------------------
data_raw <- read.csv(file_path)
## Data summary -------------------------------------------------------------------------------
# Quick checks of the data's structure
class(data_raw) # object type
head(data_raw) # print the first 6 rows
dim(data_raw) # number of rows and columns
str(data_raw) # check variable classes
summary(data_raw) # dataset summary
# Additional notes on variables
# ...
# Check for outliers
hist(data$<variable>)
hist(data$<variable>)
# Check sample sizes
test_that("Sample size", {expect_equal(length(unique(data$<variable>)), <expected_sample_size>})
# Expected sample size:
# Actual sample size:
# Check missing data
xtabs(~ <factor1> + <factor2>, data = data)
# Other applicable unit tests
test_that("<description>", {
expect_equal(...)
})
## <Analysis section title> --------------------------------------------------------------------
# This section analyses <analysis objective>.
# The data is first prepared, then visualised.
# Statistical models are fitted and predictions plotted.
## Data preparation ---------------------------------------------------------------------------
analysis_data <- data %>%
mutate(...) %>%
select(...) %>%
filter(...)
# Tests after data manipulation
test_that("<description>", {
expect_equal(...)
})
# Check structure of cleaned data
head(analysis_data)
levels(analysis_data$factor)
## Visualize raw data --------------------------------------------------------------------------
# Aggregate the data in a meaningful way for visualization
summary_data <- aggregate(...)
head(summary_data)
## Raw data figure -----------------------------------------------------------------------------
raw_plot <- ggplot(...) +
...
# View figure
raw_plot
# Save to outputs
if(save_figures) {
ggsave(filename = "output/fig/<figure_name>.png",
plot = raw_plot,
width = 200,
height = 150,
units = "mm",
dpi = "print")
}
## Fit statistical model -----------------------------------------------------------------------
# <Describe chosen model>
model_step1 <- <model_function>(...)
# Check model assumptions
performance::check_model(model_step1)
# Use ANOVA to check significance of covariates
anova_step1 <- ...
# Label model
anova_step1$mod <- "<model_name>"
# Refit model dropping terms
model_step2 <- update(...)
# Test significance of updated model with ANOVA
anova_step2 <- ...
# Pick final model
model_final <- model_step2
# Check model assumptions
performance::check_model(model_final)
# View model summary
summary(model_final)
# Extract estimated coefficients as dataframe
model_results <- summary(model_final)$coefficients %>% as.data.frame()
# Save model outputs
if(save_tables) {
write.csv(model_results, file = "output/result/<model_results>.csv", row.names = TRUE)
}
## Predict -------------------------------------------------------------------------------------
# Create input data for prediction
prediction_data <- ...
# Predict variable of interest
prediction_data$pred <- predict(model_final, newdata = prediction_data, type = "<prediction type>")
# View first rows of dataset
head(prediction_data)
## Predicted vs observed figure ---------------------------------------------------------------------------
prediction_plot <- raw_plot +
...
# View plot
prediction_plot
# Save the figure
if(save_figures) {
ggsave(filename = "output/fig/<prediction_figure>.png",
plot = prediction_plot,
width = 200,
height = 150,
units = "mm",
dpi = "print"
)
}
# End of <analysis section> / script
## +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Quick and dirty: automatically turn script into Rmarkdown file but do not yet knit
knitr::spin("scripts/<analysis_script>.R", knit = FALSE)
# Converted .Rmd file to HTML in RStudio by:
# 1. Opening generated .Rmd file
# 2. Removing the final script lines
# 3. Knit -> Knit Directory -> Project directory
# 4. Knit -> Knit to HTML