-
Notifications
You must be signed in to change notification settings - Fork 14
/
04-prac4.Rmd
620 lines (382 loc) · 31.8 KB
/
04-prac4.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# Git, GitHub and RMarkdown
## Learning outcomes
By the end of this practical you should be able to:
1. Explain the use of and differences between Git and GitHub
2. Create reproduciable and open R code
3. Produce RMarkdown documents that explain code and analysis
## Recommended listening
Some of these practicals are long, take regular breaks and have a listen to some of our fav tunes each week.
[Andy](https://www.youtube.com/watch?v=AahUu7am5No)
[Adam](https://open.spotify.com/album/4h2VgrL33fb4uNrxLNN4ti?si=i1N19HOtRU2HdbjeeCUHeg) OK, this week I'm bringing the fire --- it's my new best mate, Logistics!
## Introduction
In this practical you will learn how to produce work that is open, reproducible, shareable and portable using RStudio, RMarkdown, Git and GitHub. As more and more researchers and organisations publish assocaited code with their manusripts or documents it's very imporant to become adept at using these tools.
The tools you will use are:
* RStudio is a graphical user interface (that you should already be familiar with) --- it contains a number of features which make it excellent for authoring reproducible and open geographic data science work.
* RMarkdown is a version of the Markdown markup language which enables plain text to be formatted to contain links to data, code to run, text to explain what you a producing and metadata to tell your software what kinds of outputs to generate from your markdown code. For more information on RMarkdown look [here](https://rmarkdown.rstudio.com/).
* Git is a software version control system which allows you to keep track of the code you produce and the changes that you or others make to it.
* GitHub is an online repository that allows anyone to view the code you have produced (in whatever language you choose to program in) and use/scrutinise/contribute to/comment on it.
## The three ways
There are three ways to make your RStudio project work with GitHub
1. Set up the GitHub repository, clone it to your Git then load it in RStudio --- using Git GUI
2. Create a new RStudio project and link it to GitHub --- new version control
3. If you have an existing RProject then you can link them manually --- existing project
I will show you all three, you should be able to do way 1, then way 2 using the same repository. Way 3 will have merge issues, so start with a fresh GitHub repository. It is useful if you have produced some code then want to share it at a later date. Follow what i do in the lecture.
My advice is to read the Git and GitHub parts of the practical before you start (until the [RMarkdown] section).
## Set up your GitHub
1. If you are working on your own computer, you will first need to install Git --- https://git-scm.com/ --- if you are working on the UCL Remote Desktop, you won’t need to do this as it is already installed for you.
2. Go to http://github.com, create an account and create a new repository (call it anything you like - ‘gis_code’ or something similar), making sure it is public and you check the box that says ‘initialise new repository with a README’ --- click ‘create repository’ at the bottom
```{r echo=FALSE, out.width = "700pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/github.png')
```
3. Your new repository (‘repo’) will be created and this is where you will be able to store your code online. You will notice that a README.md markdown file has also been created. This can be edited to tell people what they are likely to find in this repository.
## Using RStudio with Git
Now, as I’ve mentioned before, RStudio is totally bad-ass. Not only does it make R fun to use, but the lovely people who created it also built in support for things like git!
For a full and excellent tutorial on using Git with R Studio, watch [this webinar](https://www.rstudio.com/resources/webinars/rstudio-essentials-webinar-series-managing-part-2/)
If you don’t want to watch the vid, I’ll do a quick summary below. So, to use git, first you need to enable it in RStudio:
At the time of writing git integration *should* work within RStudio. If it doesn't try this again on your laptop.
The next part of the practical is going run through the three ways of using Git and GitHub with RStudio as I laid out in [The three ways]
## Using the Git GUI - way 1
4. Now you have created your repo online, you need to ‘clone’ it so that there is an identical copy of it in a local folder on your computer.
There are a couple of ways of doing this, but the easy one is to use the GUI that comes packaged with your git installation.
5. The first thing you need to do is copy the Clone URL for your repo from the github website --- click the green button in your repo for ‘Clone or Download’ and copy the link:
```{r echo=FALSE, out.width = "700pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/githubrepodownload.png')
```
6. Now in the windows start menu, go to Git > GUI
7. Select ‘Clone Existing Repository’ and paste the link from your GitHub account into the top box and the local directory that you want to create to store your repo in the bottom box (note, you will need to add a name for a new folder, once you have selected an existing directory, don't create a new folder in windows explorer you have to specify it in the file path).
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/gitsetup.png')
```
8. After a few moments, you should now be able to view a copy of your GitHub repo on your local machine. This is where you will be able to store all of your code and some other files for your reproducible research.
9. Open RStudio and go File > New Project > Existing Directory
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/existing.png')
```
10. Set the project working directory to what you specified in the Git GUI target directory. You have now linked your project to your local Git
>Note for later, when we try to push to GitHub from RStudio the push button might be geyed out..this is most likely due to your local Git branch not tracking (following) the GitHub branch! Ishow you how to fix this in the greyed out push button section.
## Create a new version control in RStudio - way 2
There is an easier way to set up Git and GitHub with your project, but this assumes you are starting fresh (with no code in an RProject)!
15. Under [Set up your GitHub] we made a respository on GitHub. Copy that URL.
16. Open RStudio > File New Project > Version Control > Git
17. Copy in the repository URL and provide a project directory name...but it should populate when you paste in the URL
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/easyway.png')
```
## If have have an existing project - way 3
> Start with a fesh GitHub repository, we're assuming here that you have some code and then want to share it. DO NOT SELECT a README.md file...it should be an empty GitHub repo...
11. Open RStudio and your exsiting project (or make a new one...i will make one here). In RStudio Tools > Global Options, under ‘Git/SVN’ check the box to allow version control and locate the folder on your computer where the git.exe file is located --- if you have installed git then this should be automatically there. If you make a new project make sure you create a file (`.R` or `.Rmd` through File > New File), add something to it, then save it (File > Save As) into your project folder. When it saves it should apprear in the bottom right Files window.
12. Next go Tools > Project Options > Git/SVN > and select the version control system as Git. You should now see a git tab in the environment window of RStudio (top right) and the files also appear under the Git tab. It should look something like this....
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/makeafile.png')
```
Now you will be able to use Git and GitHub as per the following instructions...you can also refer to practical 8 [GitHub last] to avoid using the shell (as i did in the lecture) and just use RStudio GUI.
## Commiting to Git
18. As well as saving (as you normally do with any file), which saves a copy to our local directory, we will also ‘commit’ or create a save point for our work on git.
19. To do this, you should click the ‘Git’ icon and up will pop a menu like the one below:
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/commit1.png')
```
You can also click the Git tab that will have appeared in the top-right window of RStudio. Up will then pop another window that looks a little like the one below:
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/commit2.png')
```
20. Stage the changes, add a commit message so you can monitor the changes you make, then click commit
21. Make some more changes to your file and save it. Click commit again then in the review changes box you will be able to see what has changed within your file. Add a comitt message and click commit:
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/commit3.png')
```
## Using Git outside RStudio
Sometimes RStudio Git can be a bit temperamental. For example, when staging the files they can take some time to appear with the ticked box (I think this is because we are working from the Network). Normally in RStudio you click the commit button, select to stage all the files, wait a few seconds then close the review changes box and commit from the buttons in the Git tab in the environment quadrant.
Alternatively if you would like to use Git but you’re working on the UCL Remote Desktop or you are experiening other problems with getting git working in RStudio, fear not, you can just use your raw Git installation.
22. In the Start Menu, open the git GUI. Start > Git > Git GUI. You should open the existing repository that you have just created.
23. Whenever you have made some changes to your files in your cloned repo, you can use git to review the changes and ‘Commit’ (save) them and then ‘Push’ them up to your master repository on GitHub.
24. To review and commit your changes, in the commit menu, simply:
a. scan for changes
b. stage them ready for committing
c. commit the changes
d. push the changes to your GitHub repo
## Push to Github
Now we can push our changes to GitHub using the up arrow either in the RStudio Git tab (envrionment quadrant), or from the review changes box (opens when you click commit).
25. To do this, first make sure you have committed any changes to your local cloned repo and then click the ‘Push’ button to whizz your code up to your master GitHub repo --- you might be prompted to enter your github username and password to enable this...
But....if the push button is greyed out go to the section [Greyed out push button]
## Pull from GitHub
26. Pull will take any changes to the global repo and bring them into your local repo. Go to your example GitHub repo (online) and click on your test file > edit this file.
27. Add a line of code or a comment, preview the changes then commit directly to the master branch.
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/pullexample.png')
```
28. Now in RStudio click the down arrow (Pull) request. Your file should update in RStudio.
If you were to update your file on GitHub and your local one in RStudio seperately you would receive an error message in RStudio when you attempted to commit.
## Troubleshooting
### Were you challenged for your password?
As of January 2019 it is possible that Git will use a credential helper provided by the operating system. So you should be asked for your GitHub username and password only once. As I am already logged into mine and I started using GitHub a while ago i'm not exactly sure when you will be asked for you details.
You can however set your usename and email manually using the git prompt.
Go Tools > Shell and enter:
```{r, eval=FALSE, cache=TRUE}
git config --global user.name 'yourGitHubUsername'
git config --global user.email 'name@provider.com'
```
These only need to be set once.
### Greyed out push button
Is your push button greyed out? Mine was when i tried to set it up within an existing project in the section [If have have an existing project] ... Fear not....
First, let's check your local repostiority (Git) is connected to a remote one (GitHub).
Open the Shell again (Tools > Shell) and enter:
```{r, eval=FALSE, cache=TRUE}
git remote -v
## output
origin https://github.com/andrewmaclachlan/example.git (fetch)
origin https://github.com/andrewmaclachlan/example.git (push)
```
The fetch and push should be your repository on GitHub. If you need to set the remote repo use:
```{r, eval=FALSE, cache=TRUE}
git remote add origin https://github.com/andrewmaclachlanc/myrepo.git
```
**Replace** my name and myrepo with your account and repo --- it's the same URL that we cloned from GitHub...
Was it setup correctly ? Yes...
Then check the current branch in RStudio (and Git) is tracking a branch on the remote repo --- mine wasn't.
```{r, eval=FALSE, cache=TRUE}
git branch -vv
## output
master 3abe929 [origin/master] test3
```
Origin/master shows that the local master is tracking the origin/master on the remote repo. If you can't see origin/master then set it using:
```{r, eval=FALSE, cache=TRUE}
git push --set-upstream origin master
```
>Origin is the repository you cloned (from GitHub) and master is the name of the branch. You might see something like...your branch is ahead of origin/master by 1 commit. This means you have commited something you are working on in you local repo (Git) that hasn't yet been pushed to GitHub (the origin) and master branch...GitHub defaults the first branch to be called master.
If you need to change the URL of your GitHub .... so where you push your local Git to the GitHub account (changing this), perhaps you have made a new GitHub repo...
```{r, eval=FALSE, cache=TRUE}
git remote set-url origin [enter your cloned URL from GitHUB here]```
```
For more trouble shooting on Git and GitHub have a look at the book [Happy Git and GitHub for the useR](https://happygitwithr.com/rstudio-git-github.html)
## Fork a repository
A *Fork* in GitHub is a copy of someone elses repository. You could use it as a base starting point for your project or to make a fix and then submit a pull request to the original owner who would then *pull* your changes to their repository.
29. You can fork a GitHub example repository from: https://github.com/octocat/Spoon-Knife
Once you fork it, you should see it in your repositories
## Branches
Each repository you make in git has a default branch but you can create new branches to isolate development of specific areas of work without affecting other branches --- like a test envrionment.
30. Go to the test repository you just forked on github. Click the branch drop down and type in the name for a new branch:
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/branch.png')
```
31. Now click on the README.md file > edit this file
32. Add some changes, preview them and complete the commit changes box at the bottom of the screen.
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/branchtest.png')
```
33. Here, we're going to commit directly to the new branch. We could have made these changes to the master branch and then made a new branch for them at this stage. Commit the changes.
34. Go to the home page of our example branch (click the branch down arrow and select your example branch). You'll see that our example branch is now 1 commit ahead of the master.
Now let's create a **pull** reqest to the master branch. If you had modified someone else's code, then you would send a reqest to them to pull in the changes. Here we are doing a pull request for ourselves --- from our example branch to our master.
35. Click New pull request.
36. At the top you will see the branches that are being compared --- the base defaults to githubs example repository, change it to yours.
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/branchcompare.png')
```
37. Now scroll down and you will see the comaparison of between the two branches. Click create pull request.
38. Select squash and merge > confirm squash and merge. This means that all our commits on the exmaple branch and squashed into one, as we only have one it doesn't matter but could be useful in future.
39. Go back to your master branch repositry and you should see the changes from the example branch have been merged.
We will show you how to publish RMarkdown documents online in a later practical.
## Back in time
You can go back in time with Git and revert to previous versions of files that you committed. This is a bit more invovled, so have a look [at this website](https://ohi-science.org/news/github-going-back-in-time) for more information.
## Health warning
To avoid merge conflicts be careful with your commits, pushes and pulls. Think about what you are doing each time. GitHub help pages are quite comprehensive... https://help.github.com/en/articles/resolving-a-merge-conflict-on-github
## RMarkdown
OK, so now you have set everything up so that you can become a reproducable research ninja! All that remains is to do some reproducable research!
For the definitive guide on R Markdown, please read [R Markdown: The Definitive Guide](https://bookdown.org/yihui/rmarkdown/) --- obviously! It will tell you everything you need to know, far beyond what I am telling you here.
The [RMarkdown for scientists](https://rmd4sci.njtierney.com) workshop by Nicholas Tierney is a really quick guide for how to use it for reproducible science.
There is also an excellent guide on the R Studio [website](https://rmarkdown.rstudio.com/lesson-1.html)
And a quick cheatsheet [here](https://github.com/rstudio/cheatsheets/raw/master/rmarkdown-2.0.pdf)
And an older one [here](http://www.rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf)
This video is also pretty good at explaining the benefits of RMarkdown
```{r echo=FALSE, fig.align='center', cache=TRUE}
knitr::include_url("https://www.youtube.com/embed/zNzZ1PfUDNk")
```
R Markdown is awesome as you can show code, explanations and results within the same document!!!! Often it could be very hard to reproduce results owing to a lack of information in the methodology / userguides or walkthrougts not matching up with the latest version of software. Think back to a time where you had to use software and consult a massive userguide in how to use it...for me it was a very painful experience. R Markdown is a big improvement as it puts all of the information in the same document, which can then be convereted into a range of different formats --- html for webpages, word documents, PDFs, blogs, books --- virtually everything! It's also not limited to R code!!! To change the code language all you have to do is edit what is between the {} in a code chunk (we cover in point 36). In R by default you get {r}, put for python you just change this to {python}!!! COOL. You've also got to have all the python software installed and the R `reticulate()` package too.. have [a look here](https://rstudio.github.io/reticulate/articles/r_markdown.html#overview) for more information.
Now, earlier on in this exercise, I got you to open a new R Script. You now need to open a new R Markdown document, you could also select an R Notebook...They are both RMarkdown documents, the notebook originally let you run code chunks that could be exectued independently, however you can also now do this if you select a markdown file. To my knowledge the only difference is that a R Notebook adds ```output: html_notebook``` in the output option in the header of the file that adds a Preview button in the tool bar. If you don't have this then the preview option will be replaced with Knit. But you can mix the output options in your header for the file to get the Preview button back if you wish to. Basically, there isn't much difference and you can manually change it with one line of code. Have a look [here](https://stackoverflow.com/questions/43820483/difference-between-r-markdown-and-r-notebook) for more infomation. For ease i'd just stick with R Markdown files
There are two ways to create an RMarkdown document
1. File > New File > R Markdown
2. You can change the type in the bottom right corner of the script window....
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/changetype.png')
```
I always use way no.1 (so use that here) and this will be populated with some example data, click Knit to see what it does...the file should load in the viewer pane, if you click the arrow and browser button it will open in an internet browser..
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/Rmakrdowneg.png')
```
### HTML
40. We are now going to insert some code from the practical last week into the new R Markdown document that i've tweaked a bit and run it...clear all of the code except the stuff between the ---
41. In RStudio, you can either select Code > Insert Chunk or you can Click the ‘Insert’ button and insert an R chunk
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/code_chunk.png')
```
42. A box will appear and in this box, you will be able to enter and run your R code. Try pasting in:
```{r warning=FALSE, cache=TRUE}
library(plotly)
library(reshape2)
library(raster)
library(weathermetrics)
GB_auto <- raster::getData('GADM',
country="GBR",
level=0,
#set the path to store your data in
path='prac4_data/',
download=TRUE)
GBclim <- raster::getData("worldclim",
res=5,
var="tmean",
#set the path to store your data in
path='prac4_data/',
download=TRUE)
month <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
names(GBclim) <- month
GBtemp <- crop(GBclim, GB_auto)
exactGB <- mask(GBtemp, GB_auto)
#WorldClim data has a scale factor of 10!
exactGB <- exactGB/10
alldf=as.data.frame(exactGB)
squishdata <- melt(alldf, measure.vars=names(alldf))
# split the data for plotly based on month
jan<-subset(squishdata, variable=="Jan", na.rm=TRUE)
jun<-subset(squishdata, variable=="Jun", na.rm=TRUE)
# give axis titles
x <- list (title = "Temperature")
y <- list (title = "Frequency")
# set the bin width
xbinsno<-list(start=-5, end=20, size = 2.5)
# plot the histogram calling all the variables we just set
ihist<-plot_ly(alpha = 0.6) %>%
add_histogram(x = jan$value,
xbins=xbinsno, name="January") %>%
add_histogram(x = jun$value,
xbins=xbinsno, name="June") %>%
layout(barmode = "overlay", xaxis=x, yaxis=y)
ihist
```
43. When including code chunks in your work, there are various options that allow you to do things like include the code, but not run it: display the output but not the code, hide warnings etc. Most of these can be input automatically by clicking the cog icon in the top-right of the chunk, or you can specify them in the code header of the chunk...if you toggle the buttons you'll see the code change in the chunk 'header'. There are also two useful icons to the right of the settings cog, the first will run all code above the current chunck (play symbol facing downwards) and the second will run the current code chunk (regular play symbol)
```{r echo=FALSE, out.width = "800pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/code_chunk_options.png')
```
### Flexdashboard
We can also change what we knit to...how about a dashboard --- this could be something like a group of related data plots or visualisations with some code and or descriptions. First you need to install the ```flexdashboard``` package and load it
```{r, warning=FALSE, cache=TRUE, eval=FALSE}
install.packages("flexdashboard")
library(flexdashboard)
```
To do so you change the YAML to...
```{r warning=FALSE, cache=TRUE, eval=FALSE}
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
runtime: flexdashboard
---
```
Then to add coloumns for the different visualisations add the following **not** in a code chunk. Here we are going to have a coloumn on the left with our histogram then a coloumn on the right with 2 data plot areas which will be empty for this demonstration...
```{r, warning=FALSE, cache=TRUE, eval=FALSE}
This is an example of an interactive dashboard...
Column {data-width=600}
-------------------------------------
### Chart 1
```
Then should be your code chunk from above with the histogram stuff in...
Underneath the code chunk add (again not in a code chunk)
```{r, warning=FALSE, cache=TRUE, eval=FALSE}
Column {data-width=400}
-------------------------------------
### Chart 2
```
The add any code you wish (in a chunk), then to place another area beneath (still in the right hand coloumn) just add ### Chart 3 beneath the code...with all code removed it should look like this...
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/flexdash.png')
```
Note that by default flexdashboard doesn't show code...to show it you need to add echo=TRUE into the R code chunk headers or set 'global' code chunk options (within the first code chunk) through:
```{r, warning=FALSE, cache=TRUE, eval=FALSE}
knitr::opts_chunk$set(echo=TRUE)
```
### Word document
How about a word document? Just change the YAML to
```{r, warning=FALSE, cache=TRUE, eval=FALSE}
---
title: "Untitled"
output: word_document
---
```
I've also removed all the coloumn stuff from the flexdashboard...should look something like this...
```{r echo=FALSE, out.width = "600pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/knitword.png')
```
### Knit options
44. Various other options and tips can be found in the full R Markdown guide on RStudio here:
* https://rmarkdown.rstudio.com/lesson-1.html
* https://rmarkdown.rstudio.com/lesson-3.html (for code chunk options)
## Adding references
This practical will focus on Mendeley, but there are guides online if you use other reference managers.
### Set up Mendeley
You need to download Mendeley (it's free) to produce a BibTeX file. Open Mendeley (from the desktop icon) and populate it with some research papers..you should just be able to download a few `.pdfs` and drag them into Mendeley. Make sure the metadata (or document details) are correct by clicking this button...
```{r echo=FALSE, out.height = "300pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/button.png')
```
And editing the fields on the right...Now...
45. Go Tools > Options > BibTex
46. Select Escape LaTex special characters, enable BibTex syncing and Create a BibTex file for your whole library or per group.
47. Select to save the BibTeX file in the same folder as your R project, otherwise R won't be able to find it
Else you can just use my BibTex file from [here](https://github.com/andrewmaclachlan/example) it's the `.bib`.
**Warning** Whilst we've excluded the special characters if they happen to be in some of the fields within Mendeley (e.g. abstracts) this will throw an error
This method will auto sync your references to the BibTex file, which you can then load in R.
If you use Zotero then follow Adam's guide in [section 4.1 here](https://rpubs.com/adam_dennett/430188)
### Add refereces into R
48. In your document add the following to the YAML header (this is what we call the top of any RMarkdown header, enclosed by ---). I beleive it stands for Yet Another Markup Language.
I've added a few extra bits...these are pretty self-explanatory (e.g table of contents, numbered sections) but have a play around.
```{r eval=FALSE, cache=TRUE}
---
title: "R Notebook"
output:
html_document:
number_sections: yes
theme: yeti
highlight: textmate
toc: yes
toc_float:
collapsed: no
smooth_scroll: yes
editor_options:
chunk_output_type: inline
bibliography: library.bib
---
```
49. Now to cite someone just use:
```{r eval=FALSE, cache=TRUE}
[@MicheleAcuto2016; @McPherson2016]
```
> **Note** that the name i've used (e.g. McPherson2016) is what Mendeley provided as the citation key for me (see the details about every document you store to find it).
50. The complete bibliography will be placed in the last section, to add a new section to the markdown document just use # and then a space (e.g. # Last section).
### References using ```citr```
If you don't want to type the code above you can also add references to R using ```citr``` package...
```{r, cache=TRUE}
library(citr)
```
51. In the ‘Addins’ menu near the top of RStudio, you should (once RStudio has been restarted) have a citr option for ‘Insert citations’ and including them in your work.
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac4_images/citr.png')
```
### YAML options
Information to help format your knitted file is contained in the YAML header at the top. In here, you can add things like tables of contents, apply specific themes, etc.
For a selection of nice themes, see go [here](http://www.datadreaming.org/post/r-markdown-theme-gallery/)
For things like adding Tables of Contents, tabbed sections (in HTML), figure and table parameters look [here](https://bookdown.org/yihui/rmarkdown/html-document.html)
### Packrat
Packrat is useful as it let's you store all of your loaded packages in a folder within your project, if you were then to move or share your project someone else could load the packages you have used (and the appopraite version) permitting them to run your code with no isses and no inflence their main R package library. You can access Packrat through the icon under the Packages tab...or Tools > Project Options..
```{r echo=FALSE, out.width = "400pt", fig.align='center', cache=TRUE}
knitr::include_graphics('prac1_images/packrat.png')
```
This practical book is build using RStudio, but as i update the packages and content every year i haven't used Packrat here. So go and check out the [documentation](http://rstudio.github.io/packrat/?version=1.2.1335&mode=desktop) for more information.
## Binder
[Binder](https://mybinder.org/) is a free platform that makes it possible to share code very easily. I've only just come across it, so i haven't personally tried it yet. But basically you can take your RProject (that is stored on GitHub) and add a bit of extra code to it that will provide a link button (called a bage), if clicked it will then take you to an RStudio cloud workspace with all your code and data loaded, meaning someone could run your analysis with one click anywhere on any device. Fore more information have a look at:
* [R binder blog post](https://kbroman.org/blog/2019/02/18/omg_binder/)
* [YouTube walkthrough](https://www.youtube.com/watch?v=wSkheV-Uqq4)
* [R Studio conference talk on reproducible research](https://resources.rstudio.com/rstudio-conf-2019/a-guide-to-modern-reproducible-data-science-with-r)
## Further reading
Since starting this little guide, I have come across this amazing [book](http://happygitwithr.com/) on using R and GitHub, by Jenny Bryan and Jim Hester. It’s brilliant --- get involved!
...Also the [GitHub guide](https://guides.github.com/activities/hello-world/)
## Feedback
Was anything that we explained unclear this week or was something really clear...let us know [here](https://forms.gle/w2GUDYc7tSavGy7r6). It's anonymous and we'll use the responses to clear any issues up in the future / adapt the material.