19 |
20 | \
21 |
22 | Alex is a Reader in Biostatistics at the University of Aberdeen and has been teaching (and learning) R for the last 20 years.
23 |
24 | - Web: https://www.abdn.ac.uk/people/a.douglas/
25 | - Twitter: https://twitter.com/Scedacity
26 | - GitHub: https://github.com/alexd106
27 |
28 | \
29 |
30 | \
31 |
32 |
50 |
51 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # alexd106.github.io
2 | An introduction to R
3 |
4 | Rendered site: https://alexd106.github.io/intro2R
5 |
--------------------------------------------------------------------------------
/R_manual_2020.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/R_manual_2020.pdf
--------------------------------------------------------------------------------
/Rmarkdown_ex1.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Formatting text in R markdown "
3 | output:
4 | html_document:
5 | css: custom.css
6 | toc: no
7 | code_folding: hide
8 | ---
9 |
10 | ```{r global_options, echo=FALSE}
11 | knitr::opts_chunk$set(message=FALSE, tidy.opts=list(width.cutoff=60))
12 | ```
13 |
14 | \
15 |
16 | OK, before we go on to the next section let's practice marking up some plain text using R markdown syntax.
17 |
18 | Create a new R markdown document in RStudio and save it with an appropriate file name on your computer (perhaps `squid_analysis.Rmd`). Make sure you fill out the 'Title' and 'Author' information and set the output option to HTML when you create your document. Next, copy and paste the text below into your R markdown document.
19 |
20 | \
21 |
22 | ```markdown
23 |
24 | Sampling and data description
25 |
26 | These data were originally collected as part of a study published in
27 | Aquatic Living Resources (Smith et al. 2005). The aim of the study was
28 | to investigate the seasonal patterns of investment in somatic and
29 | reproductive tissues in the long finned squid Loligo forbesi caught
30 | in Scottish waters. Squid were caught monthly from December
31 | 1989 - July 1991 (month and year variables). After capture, each
32 | squid was given a unique specimen code (specimen variable) and
33 | the following variables measured:
34 |
35 | body weight - weight variable
36 | sex - sex variable (only female squid are included here)
37 | individual dorsal mantle length -DML variable
38 | mantle weight measured without internal organs - eviscerate.weight variable
39 | gonads weight - ovary.weight variable
40 | nidamental gland weight - nid.weight variable.names
41 | nidamental gland length - nid.length variable
42 | digestive gland weight - dig.weight variable
43 |
44 | Each individual was also assigned a categorical measure of maturity
45 | (maturity.stage variable) ranging from 1 to 5 with 1 = immature, 5 = mature.
46 |
47 | Some interesting background information on squid morphology can be
48 | found here (https://en.wikipedia.org/wiki/Loligo_forbesii) and the
49 | following image provides a useful summary of squid anatomy
50 |
51 | ```
52 |
53 | You will also need to download [this image](images/squid_anatomy.jpg). Create a subdirectory called `images` in the same directory as your R markdown document and save the image file there (right click and then choose `save image as...` or similar). You will embed this image after your text in your R markdown document.
54 |
55 | \
56 |
57 | Now mark it up using R markdown syntax so your rendered output document looks like this.
58 |
59 | \
60 |
61 | >
Sampling and data description
62 | These data were originally collected as part of a study published in Aquatic Living Resources (Smith *et al*., 2005). The aim of the study was to investigate the seasonal patterns of investment in somatic and reproductive tissues in the long finned squid *Loligo forbesi* caught in Scottish waters. Squid were caught monthly from December 1989 - July 1991 (**month** and **year variables**). After capture, each squid was given a unique specimen code (**specimen variable**) and the following variables measured:
63 |
64 | >- **weight variable** - body weight (g)
65 | >- **sex variable** - sex (only female squid are included here)
66 | >- **DML variable** - individual dorsal mantle length (mm)
67 | >- **eviscerate.weight variable** - mantle weight measured without internal organs (g)
68 | >- **ovary.weight variable** - gonad weight (g)
69 | >- **nid.weight variable** - nidamental gland weight (g)
70 | >- **nid.length variable** - nidamental gland length (g)
71 | >- **dig.weight variable** - digestive gland weight (g)
72 |
73 | >Each individual was also assigned a categorical measure of maturity (**maturity.stage variable**) ranging from 1 to 5 with 1 = immature, 5 = mature.
74 | Some interesting background information on squid morphology can be found [here](https://en.wikipedia.org/wiki/Loligo_forbesii) and the following image provides a useful summary of squid anatomy.
75 | 
76 |
77 | \
78 |
79 | Once you're happy with marking up your text, knit your R markdown document to a HTML file. Open this file in your web browser and check all your formatting. You could also try knitting to a pdf document.
80 |
81 | \
82 |
83 | You can find the solution below (click on the 'code' button on the right)
84 |
85 | \
86 |
87 | ```{r, class.source='fold.hide', eval=FALSE}
88 |
89 | ## Sampling and data description
90 | These data were originally collected as part of a study published in Aquatic Living Resources (Smith *et al*., 2005). The aim of the study was to investigate the seasonal patterns of investment in somatic and reproductive tissues in the long finned squid *Loligo forbesi* caught in Scottish waters. Squid were caught monthly from December 1989 - July 1991 (**month** and **year variables**). After capture, each squid was given a unique specimen code (**specimen variable**) and the following variables measured:
91 |
92 | - **weight variable** - body weight (g)
93 | - **sex variable** - sex (only female squid are included here)
94 | - **DML variable** - individual dorsal mantle length (mm)
95 | - **eviscerate.weight variable** - mantle weight measured without internal organs (g)
96 | - **ovary.weight variable** - gonad weight (g)
97 | - **nid.weight variable** - nidamental gland weight (g)
98 | - **nid.length variable** - nidamental gland length (g)
99 | - **dig.weight variable** - digestive gland weight (g)
100 |
101 | Each individual was also assigned a categorical measure of maturity (**maturity.stage variable**) ranging from 1 to 5 with 1 = immature, 5 = mature.
102 |
103 | Some interesting background information on squid morphology can be found [here](https://en.wikipedia.org/wiki/Loligo_forbesii) and the following image provides a useful summary of squid anatomy.
104 | 
105 |
106 | ```
107 |
--------------------------------------------------------------------------------
/Rmarkdown_ex2.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Code chunks in R markdown"
3 | output:
4 | html_document:
5 | toc: no
6 | css: custom.css
7 | ---
8 |
9 | \
10 |
11 | During this exercise you will practice adding code chunks and inline R code to the R markdown document you created during the [previous exercise](Rmarkdown_ex1.html). The solutions to each section of the exercise can be revealed by clicking on the `Solution` button (don't be too quick to do this though!). Once you have finished you can find my version of the `.Rmd` file [here](squid_analysis.Rmd) and the rendered html document [here](squid_analysis.html). A pdf version of the document is [here](squid_analysis.pdf)
12 | \
13 |
14 | So, the first thing you will need to do is open your `squid_analysis.Rmd` file in RStudio. You will already have a nicely marked up description of the data and the morphological variables measured during the study so we will continue with data import, exploration and some simple visualisations. You will need to download the `squid1.xlsx` file from **[ Data](data.html)** link, open it in excel and save it as a tab delimited file called `squid1.txt` (as we did during the R course).
15 | \
16 |
17 | Create a code chunk named `data-import` and include some R code to import the `squid1.txt` file into R using the `read.table()` function and assign it to a variable called `squid`. Within the code chunk get R to print out the structure of the `squid` variable. Add some text below the code chunk to explain (to your future self) what you are doing. Also write some text with inline R code to state how many observations are present (hint: use the `nrow()` function) in the dataset and how many variables were measured (hint: use the `ncol()` function).
18 |
19 | \
20 |
21 |
22 | ````markdown
23 | `r ''````{r, data-import}
24 | squid <- read.table('./data/squid1.txt', header = TRUE)
25 | str(squid)
26 | ```
27 |
28 | In this dataset `r knitr::inline_expr("nrow(squid)")` squid were caught and `r knitr::inline_expr("ncol(squid)")` variables were measured
29 | for each squid. Details are shown above.
30 | ````
31 |
32 |
33 | \
34 |
35 | Perhaps you might remember from [Exercise 4](exercise_4_solution.html) that the `year`, `month` and `maturity.stage` variables were coded as integers in the original dataset (see the output from `str(squid)` above to confirm) but we want to recode them as factors. Create a new code chunk called `data-recode` and include R code to create a new variable for each of these variables in the `squid` dataframe and recode them as factors. Change the chunk option to hide this code in the rendered document. Write some text to describe that you have recoded the variables to let the reader know you've done this (even though you don't show the code in the final document).
36 |
37 | \
38 |
39 |
40 | ````markdown
41 | `r ''````{r, data-recode, echo=FALSE}
42 | # convert variables to factors
43 | squid$Fmaturity <- factor(squid$maturity.stage)
44 | squid$Fmonth <- factor(squid$month)
45 | squid$Fyear <- factor(squid$year)
46 | ```
47 |
48 | The variables `maturity.stage`, `month` and `year` were converted from integers to factors in the dataframe
49 | `squid`. These recoded variables were named `Fmaturity`, `Fmonth` and `Fyear`.
50 | ````
51 |
52 |
53 | \
54 |
55 |
56 | Next create a code chunk (give it a suitable name) and write some code to create a table of the number of observations for each year and month combination (hint: remember the ```table()``` function?) Don't forget to use the factor recoded versions of these variables. Use the `kable()` function from the `knitr` package to nicely render the table (remember you will need to use `library(knitr)` to load the package first). You might want to also include the argument `row.names = TRUE` when you use the `kable()` function so the table contains the month numbers. Another argument that is often useful to include is `format = 'markdown` which will ensure the table renders nicely in HTML and pdf formats. Write some text to highlight which year has the fewest number of observations and which year and month combinations have no observations.
57 |
58 | \
59 |
60 |
61 | ````markdown
62 | Next, let's take a look at the number of observations across years and months.
63 |
64 | `r ''````{r, data-obs}
65 | library(knitr)
66 | kable(table(squid$Fmonth, squid$Fyear), row.names = TRUE, format = 'markdown')
67 | ```
68 |
69 | Or,If you want a fancy table with the variable names (month and year) then use the pander function from the
70 | pander package. You will also have to provide the dimnames to the table and use the ftable function to
71 | 'flatten' the table.
72 |
73 | `r ''````{r, data-obs2}
74 | library(pander)
75 | mytab <- table(squid$Fmonth, squid$Fyear)
76 | names(dimnames(mytab)) <- c("Month", "Year")
77 | pander(ftable(mytab))
78 | ```
79 |
80 | In 1989 data were only collected during December and in 1991 data collection stopped in August.
81 | During 1990, no data were collected in either February or June. There are also some months that
82 | have very few observations (May 1990 and July 1991 for example) so care must be taken when
83 | modelling these data.
84 |
85 | ````
86 |
87 |
88 | \
89 |
90 | We should also create a summary table of the number of observations for each level of maturity stage for each month. Create a code chunk and include code to do this but hide the code in the rendered document using the appropriate chunk option. If you feel like it, experiment with the `kableExtra` package to alter some of the formatting (text size etc). You may need to install the package before you can use it. Again, write some text to summarise your findings.
91 |
92 | \
93 |
94 |
95 | ````markdown
96 |
97 | Number of observations each month for each of the squid maturity stages are given in the table below.
98 |
99 | `r ''````{r, maturity-obs, echo=FALSE}
100 |
101 | # using just kable
102 |
103 | kable(table(squid$Fmaturity, squid$Fmonth), row.names = TRUE)
104 |
105 | # using kableExtra (good for html output)
106 |
107 | library(kableExtra)
108 | kable(table(squid$Fmaturity, squid$Fmonth), row.names = TRUE) %>%
109 | kable_styling(bootstrap_options = "striped", font_size = 14)
110 | ```
111 |
112 | Not all maturity stages were observed in all months. Very few squid of maturity stage 1, 2 or 3
113 | were caught in the months February to May whereas maturity stages 4 and 5 were
114 | predominantly caught during these months.
115 |
116 | ````
117 |
118 |
119 | \
120 |
121 | Ok, lets produce some exploratory plots in our document. The first thing we would like to know is whether there are any unusual observations in the variables; `DML`, `weight`, `nid.length` and `ovary.weight`. Create a code chunk containing code to plot cleveland dotplots of these variables. You can either plot one after the other or split the plotting device into 2 rows and 2 columns to plot them all together. This time we would like to show the code used to create these plots. Describe what you see and come up with a plausable explanation (refer back to Exercise 4 Question 7 for a hint.)
122 |
123 | \
124 |
125 |
126 | ````markdown
127 |
128 | Now let's check for any unusual observations in the variables; `DML`, `weight`,
129 | `nid.length` and `ovary.weight`.
130 |
131 |
132 | `r ''````{r, dotplot}
133 | par(mfrow = c(2, 2))
134 | dotchart(squid$DML, main = "DML")
135 | dotchart(squid$weight, main = "weight")
136 | dotchart(squid$nid.length, main = "nid length")
137 | dotchart(squid$ovary.weight, main = "ovary weight")
138 | ```
139 |
140 | It looks like the variable `nid.length` contains an **unusually large** value. Actually, this value
141 | is biologically implausible and clearly an error. I went back and checked my field notebook and
142 | sure enough it's a typo. I was knackered at the time and accidentally inserted a zero by mistake
143 | when transcribing these data. **Doh!** This squid was identified as observation number
144 | `r knitr::inline_expr("which(squid$nid.length > 400)")` with a sample number
145 | `r knitr::inline_expr("squid$sample.no[which(squid$nid.length > 400)]")`. This observation was
146 | subsequently removed from the data set.
147 |
148 | ````
149 |
150 |
151 | \
152 |
153 | Next, produce a boxplot of the `DML` variable against `Fmaturity` to examine whether the size of the squid changes with maturity stage. Change the chunk option to supress the R code in the final document and only display the plot. Write some text to summarise the main conclusions from the plot. Also include some inline R code to report the mean value of DML for each of the maturity stages.
154 |
155 | \
156 |
157 |
158 | ````markdown
159 |
160 | Let's take a look at whether DML changes with maturity stage.
161 |
162 | `r ''````{r, maturity-dml, echo=FALSE}
163 |
164 | boxplot(DML ~ Fmaturity, data = squid, xlab = "maturity stage", ylab = "DML")
165 |
166 | ```
167 | DML was lowest for maturity stage 1 with a mean length of
168 | `r knitr::inline_expr("round(mean(squid$DM[squid$Fmaturity == 1]), digits = 2)")` mm. DML
169 | increased until maturity stage 3
170 | (mean `r knitr::inline_expr("round(mean(squid$DM[squid$Fmaturity == 3]), digits = 2)")` mm)
171 | after which it remained reasonably consistent for maturity stages 4
172 | (mean `r knitr::inline_expr(" round(mean(squid$DM[squid$Fmaturity == 4]), digits = 2)")` mm)
173 | and 5 (mean `r knitr::inline_expr("round(mean(squid$DM[squid$Fmaturity == 5]), digits = 2)")` mm).
174 |
175 | ````
176 |
177 |
178 | \
179 |
180 | It's always good practice to include a summary of the version of R you have been using as well as a list of packages loaded. An easy way to do this is include `sessionInfo()` in a code chunk at the end of your document.
181 |
182 | \
183 |
184 |
59 |
60 | \
61 |
62 | [Introduction to version control using Git and GitHub](Github_intro.html)
63 |
64 | \
65 |
66 |
67 |
--------------------------------------------------------------------------------
/_site.yml:
--------------------------------------------------------------------------------
1 | # See http://rmarkdown.rstudio.com/rmarkdown_websites.html
2 |
3 | name: "An introduction to R"
4 | output_dir: "."
5 | navbar:
6 | title: "Intro2R"
7 | # type: inverse
8 | icon: fa-home
9 | left:
10 | - text: "Setup"
11 | icon: fa-cog
12 | href: setup.html
13 | - text: "R Book"
14 | icon: fa-book
15 | menu:
16 | - text: "Web book"
17 | icon: fa-firefox
18 | href: https://intro2r.com
19 | - text: "----"
20 | - text: "PDF book"
21 | icon: fa-file-pdf
22 | href: https://github.com/alexd106/Rbook/raw/master/docs/Rbook.pdf
23 | - text: "Learn R"
24 | icon: fa-university
25 | menu:
26 | - text: "How-to"
27 | icon: fa-tv
28 | href: howto.html
29 | - text: "----"
30 | - text: "Lectures"
31 | icon: fa-chalkboard
32 | href: lectures.html
33 | - text: "Exercises"
34 | icon: fa-file-contract
35 | menu:
36 | - text: "Excercises"
37 | icon: fa-folder
38 | href: exercises.html
39 | - text: "----"
40 | - text: "Exercise solutions"
41 | icon: fa-folder
42 | href: exercise_solutions.html
43 | - text: "Data"
44 | icon: fa-download
45 | href: "data.html"
46 | - text: "Tutorials"
47 | icon: fa-desktop
48 | href: "Tutorials.html"
49 | - text: "Info"
50 | icon: fa-question-circle
51 | menu:
52 | - text: "Syllabus"
53 | icon: fa-graduation-cap
54 | href: syllabus.html
55 | - text: "----"
56 | - text: "People"
57 | icon: fa-user-friends
58 | href: "People.html"
59 | - text: "----"
60 | - text: "Resources"
61 | icon: fa-book
62 | href: "resources.html"
63 | - text: "Feedback"
64 | icon: fa-commenting
65 | href: https://forms.gle/U7MbyhRWyLomjyFY7
66 | - text: "----"
67 | - text: "Contact"
68 | icon: fa-envelope fa-lg
69 | href: People.html
70 | - text: "Source code"
71 | icon: fa-github fa-lg
72 | href: https://github.com/alexd106/intro2R
73 | - text: "Twitter"
74 | icon: fa-twitter fa-lg
75 | href: https://twitter.com/Scedacity
76 |
77 | output:
78 | html_document:
79 | theme: flatly
80 | highlight: tango
81 | toc: true
82 | toc_depth: 2
83 | toc_float:
84 | collapsed: false
85 | fig_align: center
86 | # anchor_sections = FALSE
87 | includes:
88 | in_header: GA_script.html
89 | # css: 'styles.css'
90 | # css:
91 | # - https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css
92 | # - styles.css
93 |
94 | exclude: ["LICENSE", "README.md", "*.Rproj", "*.key", "*.psd"]
--------------------------------------------------------------------------------
/course_code.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Offline exercise solutions"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r, include=FALSE}
9 | library(knitr)
10 | library(stringr)
11 | knitr::opts_chunk$set(message=FALSE, warning=FALSE, eval=TRUE, echo=FALSE)
12 | suppressPackageStartupMessages(library(dplyr))
13 | suppressPackageStartupMessages(library(stringr))
14 | source('reveal.R')
15 | ```
16 |
17 | \
18 |
19 | ```{r, reveal, echo = FALSE, eval = isFALSE(show_text12)}
20 | cat("solutions will be released as the course progresses")
21 | ```
22 |
23 | \
24 |
25 | To download the solutions for each of the exercises as individual R scripts click the relevant links below. If the code opens in a browser window then right click on the link and select 'save link as' (or similar).
26 |
27 | \
28 |
29 | ```{r sol12, results='asis', , eval = isTRUE(show_text12)}
30 | dir <- "exercise_solutions/"
31 | file_name <- list.files(dir) %>%
32 | sort %>%
33 | grep("(exercise_[12]_solution.R)", . , value=TRUE)
34 |
35 | link_name <- file_name %>%
36 | gsub("\\.R", "", .) %>%
37 | paste0(., "s") %>%
38 | gsub("_", " ", .) %>%
39 | str_to_sentence(.)
40 |
41 | paste0("- [", link_name, "](", "exercise_solutions/", file_name, ")") %>%
42 | cat(sep="\n\n")
43 | ```
44 |
45 | ```{r sol34, results='asis', , eval = isTRUE(show_text34)}
46 | dir <- "exercise_solutions/"
47 | file_name <- list.files(dir) %>%
48 | sort %>%
49 | grep("(exercise_[34]_solution.R|exercise_[34]_ggplot_solution.R)", . , value=TRUE) %>%
50 | .[c(1,3,2)]
51 |
52 | link_name <- file_name %>%
53 | gsub("\\.R", "", .) %>%
54 | paste0(., "s") %>%
55 | gsub("_", " ", .) %>%
56 | str_to_sentence(.)
57 |
58 | paste0("- [", link_name, "](", "exercise_solutions/", file_name, ")") %>%
59 | cat(sep="\n\n")
60 | ```
61 |
62 | ```{r sol56, results='asis', , eval = isTRUE(show_text56)}
63 | dir <- "exercise_solutions/"
64 | file_name <- list.files(dir) %>%
65 | sort %>%
66 | grep("(exercise_[56]_solution.R)", . , value=TRUE)
67 |
68 | link_name <- file_name %>%
69 | gsub("\\.R", "", .) %>%
70 | paste0(., "s") %>%
71 | gsub("_", " ", .) %>%
72 | str_to_sentence(.)
73 |
74 | paste0("- [", link_name, "](", "exercise_solutions/", file_name, ")") %>%
75 | cat(sep="\n\n")
76 | ```
77 |
--------------------------------------------------------------------------------
/custom.css:
--------------------------------------------------------------------------------
1 | blockquote {
2 | padding: 10px 20px;
3 | margin: 0 0 20px;
4 | font-size: 14px;
5 | border-left: 5px solid #eee;
6 | }
7 |
8 | .infobox {
9 | padding: 1em 1em 1em 4em;
10 | margin-bottom: 10px;
11 | border: 2px solid midnightblue;
12 | border-radius: 10px;
13 | background: #ffffff 5px center/3em no-repeat;
14 | }
15 |
16 | .caution {
17 | background-image: url("images/lightbulb.png");
18 | }
19 |
20 | .toggle {
21 | height: 1.55em;
22 | overflow-y: hidden;
23 | }
24 |
25 | .toggle.open {
26 | height: auto;
27 | }
28 |
--------------------------------------------------------------------------------
/data.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Data"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r, include=FALSE}
9 | library(knitr)
10 | knitr::opts_chunk$set(message=FALSE, warning=FALSE, eval=TRUE, echo=FALSE)
11 | suppressPackageStartupMessages(library(dplyr))
12 | ```
13 |
14 | ```{r zipdir, include=FALSE}
15 | if (!file.exists("data/all_data.zip")) system("rm data/all_data.zip ; zip -r data/all_data.zip data -x '*.html' -x '*.DS_Store'")
16 | ```
17 |
18 | \
19 |
20 | **Option 1: Download all the data at once.**
21 |
22 | - Create a new RStudio project for this course (call it intro2r if your imagination fails you!). If you're not sure how to create a new Project then see [Section 1.6](https://intro2r.com/rsprojs.html) of our Introduction to R book or watch [this short video](https://alexd106.github.io/intro2R/howto.html#rstudio_proj-vid).
23 |
24 | - Once you're working in your RStudio project create a new directory in your Project directory called `data` (all lowercase). You can easily create this new directory by clicking on the 'New Folder' button in the 'Files' tab in RStudio (see [Section 1.8](https://intro2r.com/dir-struct.html) of our Introduction to R book for a set-by-step guide how to do this).
25 |
26 | - Download and extract **[this zip file ](data/all_data.zip)** `r paste0("(", round(file.info("data/all_data.zip")$size/1e6, 2), " Mb)")` with all the data for the entire workshop. This may include additional datasets that we won't use. You will need to uncompress this zip file using your favourite software (most operating systems now have at least one built-in (un)compression tool).
27 |
28 | \
29 |
30 | **Option 2: Download individual datasets as needed.**
31 |
32 | - Create a new RStudio project for this course (call it intro2r if your imagination fails you!). If you're not sure how to create a new Project then see [Section 1.6](https://intro2r.com/rsprojs.html) of our Introduction to R book or watch [this short video](https://alexd106.github.io/intro2R/howto.html#rstudio_proj-vid).
33 |
34 | - Once you're working in your RStudio project create a new directory in your Project directory called `data` (all lowercase). You can easily create this new directory by clicking on the 'New Folder' button in the 'Files' tab in RStudio (see [Section 1.8](https://intro2r.com/dir-struct.html) of our Introduction to R book for a set-by-step guide how to do this).
35 |
36 | - Download individual data files as needed, saving them to the new `intro2r/data` folder you just made. Right click on the data file link below and select _Save link as..._ (or similar) to save to the desired location.
37 |
38 |
39 | ```{r, results='asis'}
40 | dir <- "data/"
41 | list.files(dir) %>%
42 | sort %>%
43 | grep("\\.html$ | *.zip", ., value=TRUE, invert=TRUE) %>%
44 | paste0(" + [", ., "](", paste0(dir, .), ")") %>%
45 | cat(sep="\n")
46 | ```
47 |
48 |
--------------------------------------------------------------------------------
/data/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/.DS_Store
--------------------------------------------------------------------------------
/data/Gigartina.CSV:
--------------------------------------------------------------------------------
1 | diameter,diatom.treat
2 | 110,ASGM
3 | 115,ASGM
4 | 110,ASGM
5 | 108,ASGM
6 | 109,ASGM
7 | 101,ASGM
8 | 101,ASGM
9 | 98,ASGM
10 | 120,ASGM
11 | 112,ASGM
12 | 99,Sexpo
13 | 95,Sexpo
14 | 99,Sexpo
15 | 111,Sexpo
16 | 98,Sexpo
17 | 100,Sexpo
18 | 94,Sexpo
19 | 96,Sexpo
20 | 102,Sexpo
21 | 101,Sexpo
22 | 100,Sstat
23 | 90,Sstat
24 | 85,Sstat
25 | 90,Sstat
26 | 90,Sstat
27 | 89,Sstat
28 | 91,Sstat
29 | 85,Sstat
30 | 93,Sstat
31 | 88,Sstat
32 | 97,Sdecl
33 | 93,Sdecl
34 | 88,Sdecl
35 | 90,Sdecl
36 | 90,Sdecl
37 | 99,Sdecl
38 | 90,Sdecl
39 | 101,Sdecl
40 | 93,Sdecl
41 | 100,Sdecl
42 |
--------------------------------------------------------------------------------
/data/TemoraBR.CSV:
--------------------------------------------------------------------------------
1 | temp,beat_rate,acclimitisation_temp
2 | 5,3.76,5
3 | 6,5.4,5
4 | 7,8,5
5 | 10,9.4,5
6 | 11,16.6,5
7 | 12,18.5,5
8 | 13,19,5
9 | 15,22.4,5
10 | 16,24.1,5
11 | 17,22.7,5
12 | 19,30.9,5
13 | 20,26.4,5
14 | 22,32.1,5
15 | 23,38.6,5
16 | 25,42.5,5
17 | 5,4.9108,10
18 | 6,4.6255,10
19 | 7.5,6.9975,10
20 | 8,11.3654,10
21 | 9,10.6462,10
22 | 12.3,18.2671,10
23 | 14.5,19.6633,10
24 | 15,17.9219,10
25 | 18,29.151,10
26 | 19,30.5581,10
27 | 20,30.5745,10
28 | 22,34.7913,10
29 | 23.5,31.5493,10
30 | 24,40.2992,10
31 | 25,42.7285,10
32 | 5.5,2.2451,20
33 | 6,5.0023,20
34 | 7,2.0581,20
35 | 9.5,5.7884,20
36 | 10,3.8272,20
37 | 12.5,7.7031,20
38 | 14,9.7238,20
39 | 16,14.8499,20
40 | 17,12.661,20
41 | 19.5,14.1365,20
42 | 21.5,14.5336,20
43 | 22,16.0512,20
44 | 23,21.568,20
45 | 24,22.3807,20
46 | 25.5,22.8027,20
47 |
--------------------------------------------------------------------------------
/data/all_data.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/all_data.zip
--------------------------------------------------------------------------------
/data/anscombe.txt:
--------------------------------------------------------------------------------
1 | x y1 y2 y3 x4 y4
2 | 10 8.04 9.14 7.46 8 6.58
3 | 8 6.95 8.14 6.77 8 5.76
4 | 13 7.58 8.74 12.74 8 7.71
5 | 9 8.81 8.77 7.11 8 8.84
6 | 11 8.33 9.26 7.81 8 8.47
7 | 14 9.96 8.1 8.84 8 7.04
8 | 6 7.24 6.13 6.08 8 5.25
9 | 4 4.26 3.1 5.39 19 12.5
10 | 12 10.84 9.13 8.15 8 5.56
11 | 7 4.82 7.26 6.42 8 7.91
12 | 5 5.68 4.74 5.73 8 6.89
13 |
--------------------------------------------------------------------------------
/data/atmosphere.txt:
--------------------------------------------------------------------------------
1 | moisture treatment
2 | 300.6 seeded
3 | 302.4 seeded
4 | 298.6 seeded
5 | 315.9 seeded
6 | 306.9 seeded
7 | 300.1 seeded
8 | 299.8 seeded
9 | 294.7 seeded
10 | 311.9 seeded
11 | 305.4 seeded
12 | 289.6 unseeded
13 | 295.6 unseeded
14 | 289.1 unseeded
15 | 275.4 unseeded
16 | 300.9 unseeded
17 | 299.5 unseeded
18 | 304.6 unseeded
19 | 298.2 unseeded
20 | 296.3 unseeded
21 | 301.4 unseeded
22 |
--------------------------------------------------------------------------------
/data/cars.txt:
--------------------------------------------------------------------------------
1 | "speed" "dist"
2 | "1" 4 2
3 | "2" 4 10
4 | "3" 7 4
5 | "4" 7 22
6 | "5" 8 16
7 | "6" 9 10
8 | "7" 10 18
9 | "8" 10 26
10 | "9" 10 34
11 | "10" 11 17
12 | "11" 11 28
13 | "12" 12 14
14 | "13" 12 20
15 | "14" 12 24
16 | "15" 12 28
17 | "16" 13 26
18 | "17" 13 34
19 | "18" 13 34
20 | "19" 13 46
21 | "20" 14 26
22 | "21" 14 36
23 | "22" 14 60
24 | "23" 14 80
25 | "24" 15 20
26 | "25" 15 26
27 | "26" 15 54
28 | "27" 16 32
29 | "28" 16 40
30 | "29" 17 32
31 | "30" 17 40
32 | "31" 17 50
33 | "32" 18 42
34 | "33" 18 56
35 | "34" 18 76
36 | "35" 18 84
37 | "36" 19 36
38 | "37" 19 46
39 | "38" 19 68
40 | "39" 20 32
41 | "40" 20 48
42 | "41" 20 52
43 | "42" 20 56
44 | "43" 20 64
45 | "44" 22 66
46 | "45" 23 54
47 | "46" 24 70
48 | "47" 24 92
49 | "48" 24 93
50 | "49" 24 120
51 | "50" 25 85
52 |
--------------------------------------------------------------------------------
/data/children.txt:
--------------------------------------------------------------------------------
1 | names sex age weight height
2 | ALFRED M 14 69 112
3 | BARBARA F 13 62 102
4 | JAMES M 12 57 83
5 | JANE F 12 59 84
6 | JOHN M 12 59 99
7 | JUDY F 14 64 90
8 | LOUISE F 12 56 77
9 | MARY F 15 66 112
10 | RONALD M 15 67 133
11 | WILLIAM M 15 66 112
12 |
--------------------------------------------------------------------------------
/data/flower.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/flower.xls
--------------------------------------------------------------------------------
/data/isthereasanta.txt:
--------------------------------------------------------------------------------
1 | Believe Age Gender Presents Behaviour
2 | FALSE 9 male 25 naughty
3 | TRUE 5 male 20 nice
4 | TRUE 4 female 30 nice
5 | TRUE 4 male 34 naughty
6 | FALSE 10 female 27 nice
7 | FALSE 10 female 43 naughty
8 | TRUE 4 male 21 naughty
9 | TRUE 6 male 23 naughty
10 | TRUE 8 female 32 nice
11 | FALSE 8 female 17 nice
12 | TRUE 5 male 41 naughty
13 | FALSE 7 male 26 naughty
14 | FALSE 9 female 35 nice
15 | FALSE 10 female 29 nice
16 | TRUE 5 male 20 nice
17 | TRUE 5 male 15 nice
18 | TRUE 4 male 15 naughty
19 | FALSE 8 male 14 nice
20 | TRUE 9 female 25 nice
21 | FALSE 7 female 26 naughty
22 | FALSE 8 male 19 naughty
23 | FALSE 8 female 32 nice
24 | TRUE 9 male 15 naughty
25 | TRUE 5 female 27 naughty
26 | TRUE 6 female 26 nice
27 | TRUE 4 male 29 nice
28 | FALSE 10 male 31 nice
29 | FALSE 9 female 30 naughty
30 | FALSE 9 female 46 nice
31 | TRUE 5 female 15 naughty
32 | FALSE 7 male 17 naughty
33 | FALSE 8 female 22 nice
34 | FALSE 8 female 34 naughty
35 | TRUE 4 female 19 naughty
36 | TRUE 5 male 27 nice
37 | TRUE 6 male 32 nice
38 | FALSE 7 male 12 naughty
39 | FALSE 10 female 20 nice
40 | FALSE 9 female 34 naughty
41 | FALSE 8 male 26 naughty
42 | TRUE 5 female 38 nice
43 | TRUE 4 male 42 nice
44 | FALSE 8 male 35 nice
45 | FALSE 9 male 26 naughty
46 | TRUE 6 male 34 naughty
47 | TRUE 4 male 34 naughty
48 | TRUE 4 female 23 naughty
49 | FALSE 7 female 27 naughty
50 | TRUE 10 male 57 nice
51 | FALSE 4 male 3 naughty
52 |
--------------------------------------------------------------------------------
/data/loyn.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/loyn.xlsx
--------------------------------------------------------------------------------
/data/pollution.txt:
--------------------------------------------------------------------------------
1 | down up
2 | 20 23
3 | 15 16
4 | 10 10
5 | 5 4
6 | 20 22
7 | 15 15
8 | 10 12
9 | 5 7
10 | 20 21
11 | 15 16
12 | 10 11
13 | 5 5
14 | 20 22
15 | 15 14
16 | 10 10
17 | 5 6
18 |
--------------------------------------------------------------------------------
/data/prawnGR.CSV:
--------------------------------------------------------------------------------
1 | GRate,diet
2 | 9.7741,Natural
3 | 10.2931,Natural
4 | 10.0474,Natural
5 | 10.0808,Natural
6 | 9.3106,Natural
7 | 10.4414,Natural
8 | 9.846,Natural
9 | 10.2709,Natural
10 | 9.5243,Natural
11 | 9.5238,Natural
12 | 9.9583,Natural
13 | 9.7703,Natural
14 | 10.1506,Natural
15 | 10.0985,Natural
16 | 10.261,Natural
17 | 9.2053,Natural
18 | 10.9352,Natural
19 | 11.6317,Natural
20 | 9.685,Natural
21 | 9.7422,Natural
22 | 11.2128,Natural
23 | 10.5183,Natural
24 | 10.3186,Natural
25 | 8.6495,Natural
26 | 9.7894,Natural
27 | 9.9268,Natural
28 | 10.9515,Natural
29 | 10.0512,Natural
30 | 9.6838,Natural
31 | 9.7254,Natural
32 | 9.5585,Artificial
33 | 10.657,Artificial
34 | 10.2424,Artificial
35 | 9.4472,Artificial
36 | 10.6712,Artificial
37 | 10.2044,Artificial
38 | 10.4935,Artificial
39 | 9.966,Artificial
40 | 9.782,Artificial
41 | 11.0716,Artificial
42 | 9.1151,Artificial
43 | 10.0486,Artificial
44 | 10.925,Artificial
45 | 9.8355,Artificial
46 | 9.6948,Artificial
47 | 9.0871,Artificial
48 | 10.4186,Artificial
49 | 8.0696,Artificial
50 | 9.8316,Artificial
51 | 9.2525,Artificial
52 | 8.8289,Artificial
53 | 9.4892,Artificial
54 | 10.7487,Artificial
55 | 10.7183,Artificial
56 | 8.9992,Artificial
57 | 8.9554,Artificial
58 | 9.5803,Artificial
59 | 10.4603,Artificial
60 | 7.3952,Artificial
61 | 10.2763,Artificial
62 |
--------------------------------------------------------------------------------
/data/seeds.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/seeds.xls
--------------------------------------------------------------------------------
/data/smoking.txt:
--------------------------------------------------------------------------------
1 | occupational.group risk.group smoking mortality
2 | Farmers low 77 84
3 | Miners high 137 116
4 | Chemical.makers high 117 123
5 | Glass.makers medium 94 128
6 | Furnac.workers high 116 155
7 | Electrical.workers medium 102 101
8 | Engineering medium 111 118
9 | Woodworkers medium 93 113
10 | Leather.workers medium 88 104
11 | Textile.workers medium 102 88
12 | Clothing.workers low 91 104
13 | Tobacco.workers high 104 129
14 | Paper.workers medium 107 86
15 | Other.products medium 112 96
16 | Construction.workers high 113 144
17 | Painters high 110 139
18 | Crane.Drivers medium 125 113
19 | Laborers high 133 146
20 | Transport.workers high 115 128
21 | Warehousemen medium 105 115
22 | Clerical.workers low 87 79
23 | Sales.workers low 91 85
24 | Recreation.workers medium 100 120
25 | Administrators low 76 60
26 | Professionals low 66 51
--------------------------------------------------------------------------------
/data/squid1.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/squid1.xlsx
--------------------------------------------------------------------------------
/data/wedgeclamII.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/wedgeclamII.xlsx
--------------------------------------------------------------------------------
/data/whaledata.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/data/whaledata.xls
--------------------------------------------------------------------------------
/delegate_email:
--------------------------------------------------------------------------------
1 | Dear all QUADRAT R users,
2 |
3 | As the 'Introduction to R' course is almost upon us I thought I would let you know a little more about the course and some logistical arrangements.
4 |
5 | The main aim of this course is to gently introduce you to using R (and RStudio) so you can start using it to visualise, summarise and analyse data collected during your PhD (and beyond). The course assumes no previous experience or knowledge of R, although if you do have some experience I hope the course will be sufficiently flexible that you will still find it productive. The course is very 'hands-on' with plenty of opportunity to practice what you have learned in a supportive and relaxed environment. You can find all of the course material at the companion website (some material will be released when the course starts):
6 |
7 | https://alexd106.github.io
8 |
9 | The course will start at 09:30 each morning and finish at 17:00. We will break for a one hour lunch break around 12:00 and there will also be plenty of opportunities to take short breaks during the course. All teaching will be held in room FN113 in the Fraser Noble building (see the course website for a map). For those of you unfamiliar with the University of Aberdeen, there are plenty of places to grab a bite to eat (or get a caffeine hit) and I have indicated these on the map (or ask one of your fellow Aberdeen QUADRATers).
10 |
11 | A couple of things before you arrive next week. Please make sure you have obtained a University of Aberdeen IT account prior to arrival (please email Izzie if you are having any issues). Please bring your own laptop with the latest versions of R and RStudio installed. I have provided information on how to do this on the course website under the 'Setup' tab. Also, don't forget your laptop charging cable! Don't worry if you're having trouble installing software, I will run a drop-in session on Monday 2nd December 14:00 - 15:30 in room 113 Fraser Noble building to troubleshoot any issues. If you don't have a laptop you will be able to use one of the University Desktops (we have 10 available).
12 |
13 | That's about it. If you have any further questions please get in touch (a.douglas@abdn.ac.uk) and I look forward to meeting you all nest week.
14 |
15 | Cheers
16 | Alex
17 |
--------------------------------------------------------------------------------
/exercise_1.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Exercises"
3 | output:
4 | html_document:
5 | toc: no
6 | ---
7 |
8 |
9 | ```{r setup, echo=FALSE}
10 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
11 | ```
12 |
13 | \
14 |
15 | ## Exercise 1 : Getting to know R and RStudio
16 |
17 | \
18 |
19 | Read [Chapter 1](https://intro2r.com/chap1.html) to help you complete the questions in this exercise. We'll also bounce occasionally to [Chapter 2](https://intro2r.com/basics_r.html) for a few questions where links will be provided.
20 |
21 | \
22 |
23 | 1. Start RStudio on your computer. Create a new RStudio Project (select File --> New Project on the main menu). Create the Project in a new directory by selecting 'New Directory' and then select 'New Project'. Give the Project a suitable name in the 'Directory name:' box (maybe 'BI5009_statistics'? - see [Section 1.9](https://intro2r.com/file_names.html) of the Introduction to R book for a discussion on naming files and directories). Choose where you would like to create this Project directory by clicking on the 'Browse' button. Finally create the project by clicking on the 'Create Project' button. This will be your main RStudio Project file and directory which you will use throughout this course. If you're confused see [Section 1.6](https://intro2r.com/rsprojs.html) of the introduction to R Book which covers RStudio Projects or watch the 'RStudio Projects' video [here](https://alexd106.github.io/BI5009/howto.html#rstudio_proj-vid).
24 |
25 | \
26 |
27 | 2. Now create a new R script inside this Project by selecting File --> New File --> R Script from the main menu (or use the shortcut button). Before you start writing any code save this script by selecting File --> Save from the main menu. Call this script 'exercise_1' or something similar (remember, files names should not [contain spaces!](https://intro2r.com/file_names.html)). Click on the 'Files' tab in the bottom right RStudio pane to see whether your file has been saved in the correct location. Ok, at the top of almost every R script (there are very few exceptions to this!) you should include some metadata to help your collaborators (and the future you) know who wrote the script, when it was written and what the script does (amongst other things). Include this information at the top of your R script making sure that you place a `#` at the beginning of every line to let R know this is a comment. See [Section 1.10](https://intro2r.com/proj-doc.html) for a little more detail.
28 |
29 | \
30 |
31 | 3. Explore RStudio making sure you understand the functionality of each of the four windows. Take a look at [Section 1.3](https://intro2r.com/rstudio_orient.html) of the Introduction to R book for more details or watch this [video](https://alexd106.github.io/BI5009/howto.html#rstudio-vid). Take your time and check out each of the tabs in the windows. The function of some of these tabs will be obvious whereas others won't be useful right now. In general, you will write your R code in the script editor window (usually top left window) and then source your code into the R console (usually bottom left) by clicking anywhere in the relevant line of code with your mouse and then clicking on the 'Run' button at the top of the script editor window. If you don't like clicking buttons (I don't!) then you can use the keyboard shortcut 'ctrl + enter' (on Windows) or 'command + enter' (on Mac OSX).
32 |
33 | \
34 |
35 | 4. Now to practice writing code in the script editor and sourcing this code into the R console. Let's display the help file for the function `mean`. In your script type `help('mean')` and source this code into the console. Notice that the help file is displayed in the bottom right window (if not then click on the 'Help' tab). Examine the different components of the help file (especially the examples section at the end of the help file). See [Section 2.5](https://intro2r.com/help.html) of the Introduction to R book for more details on using the help functions.
36 |
37 | \
38 |
39 | 5. The content displayed in the bottom right window is context dependent. For example if we write the code `plot(1:10)` in our script and then source it into the R console the bottom right window will display this plot (don't worry about understanding the R code right now, hopefully this will become clear later on in the course!).
40 |
41 | \
42 |
43 | 6. Next, let's practice creating a variable and assigning a value to this variable. Take a look at [Section 2.2](https://intro2r.com/objects-in-r.html) of the Introduction to R book for further information on how to do this or if you prefer watch the [Objects in R video](https://alexd106.github.io/BI5009/howto.html#objs-vid). Create a variable called `first_num` and assign it the value `42`. Click on the 'Environment' tab in the top right window to display the variable and value. Now create another variable called `first_char` and assign it a value `"my first character"`. Notice this variable is now also displayed in the 'Environment' along with it's value and class (`chr` - short for character class).
44 |
45 | \
46 |
47 | 7. Remove the variable `first_num` from your environment using the `rm()` function. Use the code `rm(first_num)` to do this. Check out the 'Environment' tab to ensure the variable has been removed. Alternatively, use the `ls()` function to list all objects in your environment.
48 |
49 | \
50 |
51 | 8. Let's see what happens if we assign another value to an existing variable. Assign the value `"my second character"` to the variable `first_char` you created in Q6. Notice the value has changed in the 'Environment'. To display the value of `first.char` enter the name of the variable in the console. Don't to forget to save your R script periodically!
52 |
53 | \
54 |
55 | 9. OK, let's leave RStudio for a minute. Using your favourite web browser, navigate to the [R-project website](http://www.r-project.org) and explore links that catch your eye. Make sure you find the R manuals page and the user contributed documents section. Download any manuals that you think you might find useful (some are listed in the course manual) and save them on your computer (or USB drive).
56 |
57 | \
58 |
59 | 10. Click on the 'Search' link on the R-Project website. Use 'Rseek' to search for the term 'mixed model p values' (this is a controversial subject!) and explore anything that looks interesting. Learning how to search for help when you run into a problem when using R is an acquired skill and something you get better at over time. One note of caution, often you'll find many different solutions to solving a problem in R, some written by experienced R users and others by people with less experience. Whichever solution you choose make sure you understand what the code is doing and thoroughly test it to make sure it's doing what you want.
60 |
61 | \
62 |
63 | 11. OK, back to RStudio. Sometimes you may forget the exact name of a function you want to use so it would be useful to be able to search through all the function names. For example, you want to create a design plot but can only remember that the name of the function has the word 'plot' in it. Use the `apropos()` function to list all the functions with the word plot in their name (see [Section 2.5.1](https://intro2r.com/help.html#help) of the Introduction to R book). Look through the list and once you have figured what the correct function is then bring up the help file for this function (Hint: the function name probably has the words 'plot' and 'design' in it!).
64 |
65 | \
66 |
67 | 12. Another strategy would be to use the `help.search()` function to search through R's help files. Search the R help system for instances of the character string ‘plot’. Take a look at [Section 2.5.1](https://intro2r.com/help.html#r-help) for more information. Also, see if you can figure out how to narrow your search by only searching for ‘plot’ in the `nlme` package (hint: see the help page for `help.search()`).
68 |
69 | \
70 |
71 | 13. R's working directory is the default location of any files you read into R, or export from R. Although you won't be importing or exporting files just yet (that's tomorrows job) it's useful to be able to determine what your current working directory is. So, read [Section 1.7](https://intro2r.com/work-d.html) of the Introduction to R book to introduce yourself to working directories and figure out how to display your current working directory.
72 |
73 | \
74 |
75 | 14. Let's finish up by creating some additional useful directories in your Project directory. If you've followed the **Data ** instructions when downloading datasets for this course you will already have a directory called `data` in your Project (if you didn't then take a look at the instructions under **Data ** to create this directory). Now let's create another directory called `output` where you'll save data files and plots you generate later on during this course. This time, instead of clicking on the 'New Folder' icon in RStudio we'll create a new directory using R code directly in the R console (you can also interact with your computer's operating system in all sorts of useful ways). To do this use the `dir.create()` function to create a directory called `output` (See [Section 1.8](https://intro2r.com/dir-struct.html) of the Introduction to R book for more details). If you fancy it, you can also create a subdirectory in your `output` directory called `figures` to store all your fancy R plots for your thesis. You can list all the files in your directories using the `list.files()` function. Can you figure out how to list the directories as well? (hint: see `?listfiles` or [Section 1.8](https://intro2r.com/dir-struct.html) of the course book).
76 |
77 | \
78 |
79 | 15. Don't to forget to save your R script. Close your Project by selecting File --> Close Project on the main menu.
80 |
81 | \
82 |
83 | End of Exercise 1
84 |
--------------------------------------------------------------------------------
/exercise_2.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Exercises"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r setup, echo=FALSE}
9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
10 | ```
11 |
12 | \
13 |
14 | ## Exercise 2 : Basic R operations
15 |
16 | \
17 |
18 | Read [Chapter 2](https://intro2r.com/basics-r.html) to help you complete the questions in this exercise.
19 |
20 | \
21 |
22 | 1. Open up your RStudio Project from Exercise 1 and either create a new R script or continue with your previous R script. Remember to save your R script with a suitable name (exercise_2?). Make sure you include any metadata you feel is appropriate (title, description of task, date of script creation etc). Don't forget to comment out your metadata with a `#` at the beginning of the line.
23 |
24 | \
25 |
26 | 2. Let's use R as a fancy calculator. Find the natural log, log to the base 10, log to the base 2, square root and the natural antilog of 12.43. See [Section 2.1](https://intro2r.com/getting-started.html#getting-started) of the Introduction to R book for more information on mathematical functions in R. Don't forget to write your code in RStudio's script editor and source the code into the console.
27 |
28 | \
29 |
30 | 3. Next, use R to determine the area of a circle with a diameter of 20 cm and assign the result to an object called `area_circle`. If you can't remember how to create and assign objects see [Section 2.2](https://intro2r.com/objects-in-r.html#objects-in-r) or watch this [video](https://alexd106.github.io/BI5009/howto.html#objs-vid). Google is your friend if you can't remember the formula to calculate the area of a circle! Also, remember that R already knows about `pi`. Don’t worry if you’re stumped and feel free to ask one of the instructors for guidance.
31 |
32 | \
33 |
34 | 4. Now for something a little more tricky. Calculate the cube root of 14 x 0.51. You might need to think creatively for a solution (hint: think exponents), and remember that R follows the usual order of mathematical operators so you might need to use brackets in your code (see [this page ](https://en.wikipedia.org/wiki/Order_of_operations) if you've never heard of this). The point of this question is not to torture you with maths (so please don't stress!), its to get you used to writing mathematical equations in R and highlight the order of operations.
35 |
36 | \
37 |
38 | 5. Ok, you're now ready to explore one of R's basic (but very useful) data structures - vectors. A vector is a sequence of elements (or components) that are all of the same data type (see [Section 3.2.1](https://intro2r.com/data-structures.html#scal_vecs) for an introduction to vectors). Although technically not correct it might be useful to think of a vector as something like a single column in a spreadsheet. There are a multitude of ways to create vectors in R but you will use the concatenate function `c()` to create a vector called `weight` containing the weight (in kg) of 10 children: `69, 62, 57, 59, 59, 64, 56, 66, 67, 66` ([Section 2.3](https://intro2r.com/using-functions-in-r.html#using-functions-in-r) or watch this [video](https://alexd106.github.io/BI5009/howto.html#vec-vid) for more information).
39 |
40 | \
41 |
42 | 6. Now you can do some useful stuff to your `weight` vector. Get R to calculate the mean, variance, standard deviation, range of weights and the number of children of your `weight` vector (see [Section 2.3](https://intro2r.com/using-functions-in-r.html) for more details). Now read [Section 2.4](https://intro2r.com/vectors.html) of the R book to learn how to work with vectors. After reading this section you should be able to extract the weights for the first five children using [Positional indexes](https://intro2r.com/vectors.html#positional-index) and store these weights in a new variable called `first_five`. Remember, you will need to use the square brackets `[ ]` to extract (aka index, subset) elements from a variable.
43 |
44 | \
45 |
46 | 7. We're now going to use the the `c()` function again to create another vector called `height` containing the height (in cm) of the same 10 children: `112, 102, 83, 84, 99, 90, 77, 112, 133, 112`. Use the `summary()` function to summarise these data in the `height` object. Extract the height of the 2nd, 3rd, 9th and 10th child and assign these heights to a variable called `some_child` (take a look at the section [Positional indexes](https://intro2r.com/vectors.html#positional-index) in the R book if you're stuck). We can also extract elements using [Logical indexes](https://intro2r.com/vectors.html#logical-index). Let's extract all the heights of children less than or equal to 99 cm and assign to a variable called `shorter_child`.
47 |
48 | \
49 |
50 | 8. Now you can use the information in your `weight` and `height` variables to calculate the body mass index (BMI) for each child. The BMI is calculated as weight (in kg) divided by the square of the height (in meters). Store the results of this calculation in a variable called `bmi`. Note: you don’t need to do this calculation for each child individually, you can use both vectors in the BMI equation – this is called vectorisation (see [Section 2.4.4](https://intro2r.com/vectors.html#vectorisation) of the Introduction to R book).
51 |
52 | \
53 |
54 | 9. Now let's practice a very useful skill - creating sequences (honestly it is...). Take a look at [Section 2.3](https://intro2r.com/using-functions-in-r.html#using-functions-in-r) in the R book (the bit on creating sequences) to see the myriad ways you can create sequences in R. Let's use the `seq()` function to create a sequence of numbers ranging from 0 to 1 in steps of 0.1 (this is also a vector by the way) and assign this sequence to a variable called `seq1`.
55 |
56 | \
57 |
58 | 10. Next, see if you can figure out how to create a sequence from 10 to 1 in steps of 0.5. Assign this sequence to a variable called `seq2` (Hint: you may find it useful to include the `rev()` function in your code).
59 |
60 | \
61 |
62 | 11. Let's go sequence crazy! Generate the following sequences. You will need to experiment with the arguments to the `rep()` function to generate these sequences (see [Section 2.3](https://intro2r.com/using-functions-in-r.html#using-functions-in-r) for some clues):
63 |
64 | - 1 2 3 1 2 3 1 2 3
65 | - "a" "a" "a" "c" "c" "c" "e" "e" "e" "g" "g" "g"
66 | - "a" "c" "e" "g" "a" "c" "e" "g" "a" "c" "e" "g"
67 | - 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3
68 | - 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
69 | - 7 7 7 7 2 2 2 8 1 1 1 1 1
70 |
71 | \
72 |
73 | 12. Ok, back to the variable `height` you created in Q7. Let's sort the values of `height` into ascending order (shortest to tallest) and assign the sorted vector to a new variable called `height_sorted`. Take a look at [Section 2.4.3](https://intro2r.com/vectors.html#vec_ord) in the R book to see how to do this. Now sort all heights into descending order and assign the new vector a name of your choice.
74 |
75 | \
76 |
77 | 13. Let's give the children some names. Create a new vector called `child_name` with the following names of the 10 children: `"Alfred", "Barbara", "James", "Jane", "John", "Judy", "Louise", "Mary", "Ronald", "William"`.
78 |
79 | \
80 |
81 | 14. A really useful (and common) task is to order the values of one variable by the order of another variable. To do this you will need to use the `order()` function in combination with the square bracket notation `[ ]`. Have a peep at [Section 2.4.3](https://intro2r.com/vectors.html#vec_ord) for some details. Create a new variable called `names_sort` to store the names of the children ordered by child height (from shortest to tallest). Who is the shortest? who is the tallest child? If you're not sure how to do this, please ask one of the instructors.
82 |
83 | \
84 |
85 | 15. Now order the names of the children by **descending** values of weight and assign the result to a variable called `weight_rev` (Hint: perhaps include the `rev()` function?). Who is the heaviest? Who is the lightest?
86 |
87 | \
88 |
89 | 16. Almost there! In R, missing values are usually represented with an `NA`. Missing data can be tricky to deal with in R (and in statistics more generally) and cause some surprising behaviour when using some functions. Take a look at [Section 2.4.5](https://intro2r.com/vectors.html#na_vals) of the R book for more information about missing values. To explore this a little further let's create a vector called `mydata` with the values `2, 4, 1, 6, 8, 5, NA, 4, 7`. Notice the value of the 7^th^ element of `mydata` is missing. Now use the `mean()` function to calculate the mean of the values in `mydata`. What does R return? Confused? Next, take a look at the help page for the function `mean()`. Can you figure out how to alter your use of the `mean()` function to calculate the mean without this missing value?
90 |
91 | \
92 |
93 | 17. Finally, list all variables in your workspace that you have created in this exercise. Remove the variable `seq1` from the workspace using the `rm()` function.
94 |
95 | \
96 |
97 | End of Exercise 2
--------------------------------------------------------------------------------
/exercise_4_ggplot_solution.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Exercise Solutions'
3 | output:
4 | html_document:
5 | toc: false
6 | code_folding: hide
7 | ---
8 |
9 |
10 | ```{r setup, echo=FALSE, purl = FALSE}
11 | knitr::opts_chunk$set(echo=TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
12 | ```
13 |
14 | \
15 |
16 | ## Exercise: Graphical data exploration using R
17 |
18 | \
19 |
20 | Alternative solutions to Exercise 4 for those who use (or are interested in using) the ```ggplot``` approach to plotting data.
21 |
22 | \
23 |
24 | End of Graphical data exploration using R Exercise
25 |
--------------------------------------------------------------------------------
/exercise_5.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Exercises"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r setup, echo=FALSE}
9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
10 | ```
11 |
12 | \
13 |
14 | ## Exercise 5: Basic statistics in R
15 |
16 | \
17 |
18 | Read [Chapter 6](https://intro2r.com/stats_r.html) to help you complete the questions in this exercise.
19 |
20 | \
21 |
22 | Although this short course is primarily focussed on introducing you to R, it wouldn't be complete if we didn't have a quick peek at some of R's statistical roots. Having said that, this will be a very brief overview with very little in the way of theory so don't worry if you get a little lost - this is just a taster, the main course is still to come!
23 |
24 | \
25 |
26 | 1\. Download the datafile *'prawnGR.CSV'* from the **[ Data](data.html)** link and save it to the `data` directory. Import these data into R and assign to a variable with an appropriate name. These data were collected from an experiment to investigate the difference in growth rate of the [giant tiger prawn](https://en.wikipedia.org/wiki/Penaeus_monodon) (*Penaeus monodon*) fed either an artificial or natural diet. Have a quick look at the structure of this dataset and plot the growth rate versus the diet using an appropriate plot. How many observations are there in each diet treatment?
27 |
28 | \
29 |
30 | 2\. You want to compare the difference in growth rate between the two diets using a two sample t-test. Before you conduct the test, you need to assess the normality and equal variance assumptions. Use the function `shapiro.test()` to assess normality of growth rate for each diet separately (Hint: use your indexing skills to extract the growth rate for each diet `GRate[diet=='Natural']` first). Use the function `var.test()` to test for equal variance (see `?var.test` for more information or [Section 6.1](https://intro2r.com/one-and-two-sample-tests.html#one-and-two-sample-tests) of the book for more details). Are your data normally distributed and have equal variances? Note: We don't really advocate using these 'approaches' for assessing the normality and equal variance assumptions assumptions but include them here as many people will still want to use them. A much better way to assess assumptions is to use diagnostic plots of the residuals (see Q6 for an example).
31 |
32 | \
33 |
34 | 3\. Conduct a two sample t-test using the `t.test()` function ([Section 6.1](https://intro2r.com/one-and-two-sample-tests.html#one-and-two-sample-tests)of the book). Use the argument `var.equal = TRUE` to perform the t-test assuming equal variances. What is the null hypothesis you want to test? Do you reject or fail to reject the null hypothesis? What is the value of the t statistic, degrees of freedom and p value? How would you summarise these summary statistics in a report?
35 |
36 | \
37 |
38 | 4\. An alternative (but equivalent) way to compare the mean growth rate between diets is to use a linear model. Use the `lm()` function to fit a linear model with `GRate` as the response variable and `diet` as an explanatory variable (see [Section 6.3](https://intro2r.com/simple-lm.html#simple_lm) for a very brief introduction to linear modelling). Assign (`<-`) the results of the linear model to a variable with an appropriate name (i.e. `growth.lm`).
39 |
40 | \
41 |
42 | 5\. Produce an ANOVA table for the fitted model using the `anova()` function i.e. `anova(growth.lm)`. Compare the ANOVA p value to the p value obtained using a t-test. What do you notice? What is the value of the F statistics and degrees of freedom? How would you summarise these results in a report?
43 |
44 | \
45 |
46 | 6\. Assess the normality and equal variance assumptions by plotting the residuals of the fitted model (see [Section 6.3](https://intro2r.com/simple-lm.html#simple_lm) for more details). Split the plotting device into 2 rows and 2 columns using `par(mfrow=c(2,2))` so you can fit four plots on a single device. Use the `plot()` function on your fitted model (`plot(growth.lm)`) to plot the graphs. Discuss with an instructor how to interpret these plots. What are your conclusions?
47 |
48 | \
49 |
50 | 7\. Download the datafile *'Gigartina.CSV'* from the **[ Data](data.html)** link and save it to the `data` directory. Import the dataset into R and assign the dataframe an appropriate name. These data were collected from a study to examine the change in `diameter` of red algae [*Mastocarpus stellatus*](https://en.wikipedia.org/wiki/Mastocarpus_stellatus) spores grown in three different diatom cultures and a control group grown in artificial seawater (`diatom.treat` variable). Use the function `str()` to examine the dataframe. How many replicates are there per diatom treatment? Use an appropriate plot to examine whether there are any obvious differences in diameter between the treatments.
51 |
52 | \
53 |
54 | 8\. You wish to compare the mean diameter of *Metacarpus* grown in the four treatment groups (`ASGM`, `Sdecl`, `Sexpo`, `Sstat`) using a one-way analysis of variance (ANOVA). What is your null hypothesis?
55 |
56 | \
57 |
58 | 9\. We will conduct the ANOVA using the linear model function `lm()` once again. Make sure you know which of the variables is your response variable and which is your explanatory variable (ask an instructor if in doubt). Fit the linear model and assign the model output to a variable with an appropriate name (i.e. `gigartina.lm`).
59 |
60 | \
61 |
62 | 10\. Produce an ANOVA table using the `anova()` function. What is the value of the p value? Do you reject or fail to reject the null hypothesis? What is the value of the *F* statistic and degrees of freedom? How would you report these summary statistics in a report?
63 |
64 | \
65 |
66 | 11\. Assess the assumptions of normality and equal variance of the residuals by producing the residual plots as before. Don’t forget to split the plotting device into 2 rows and 2 columns before plotting. Discuss with an instructor whether the residuals meet these assumptions. Do you accept this model as acceptable?
67 |
68 | \
69 |
70 | 12\. Let’s compare the treatment group means to determine which treatment group is different from other treatment groups. In general, you should be careful with these types of post-hoc comparisons, especially if you have a large number of groups (There are much better ways to do this, but that's for another course!). In this case we only have 4 groups, and therefore we will use Tukey’s Honest significant difference to perform the comparisons and control for type 1 error rate (rejecting a true null hypothesis).
71 |
72 | \
73 |
74 | 13\. We will use the function `TukeyHSD()` from the `mosaic` package to perform these comparisons (you will need to install this package first and then use `library(mosaic)` to make the function available). Which groups are different from each other if we use the p-value cutoff (alpha) of p < 0.05?
75 |
76 | \
77 |
78 | 14\. We can also produce a plot of the comparisons to help us interpret the table of comparisons. Use the `plot()` function with the `TukeyHSD(gigartina.lm)`. Ask if you get stuck (or Google it!).
79 |
80 | \
81 |
82 | 15\. Download the *'TemoraBR.csv'* file from the **[ Data](data.html)** link and save it to the `data` directory. Import the dataset into R and as usual assign it to a variable. These data are from an experiment that was conducted to investigate the relationship between temperature (`temp`) and the beat rate (Hz) `beat_rate` of the copepod [*Temora longicornis*](https://en.wikipedia.org/wiki/Temora_longicornis) which had been acclimatised at three different temperature regimes (`acclimitisation_temp`). Examine the structure of the dataset. How many variables are there? What type of variables are they? Which is the response (dependent) variable, and which are the explanatory (independent) variables?
83 |
84 | \
85 |
86 | 16\. What type of variable is `acclimitisation_temp`? Is it a factor? Convert `acclimitisation_temp` to a factor and store the result in a new column in your dataframe called `Facclimitisation_temp`. Hint: use the function `factor()`. Use an appropriate plot to visualise these data (perhaps a coplot or similar?).
87 |
88 | \
89 |
90 | 17\. We will analyse these data using an Analysis of Covariance (ANCOVA) to compare the slopes and the intercepts of the relationship between `beat_rate` and `temp` for each level of `Facclimatisation_temp`. Take a look at the plot you produced in Q16, do you think the relationships are different?
91 |
92 | \
93 |
94 | 18\. As usual we will fit the model using the `lm()` function. You will need to fit the main effects of `temp` and `Facclimatisation_temp` and the interaction between `temp` and `Facclimatisation_temp`. You can do this using either of the equivalent specifications:
95 |
96 | `temp + Facclimatisation_temp + temp:Facclimatisation_temp` or
97 |
98 | `temp * Facclimatisation_temp`
99 |
100 | \
101 |
102 | 19\. Produce the summary ANOVA table as usual. Is the interaction between `temp` and `Facclimatisation_temp` significant? What is the interpretation of the interaction term? Should we interpret the main effects of ```temp``` and `Facclimatisation_temp` as well?
103 |
104 | \
105 |
106 | 20\. Assess the assumptions of normality and equal variance of the residuals in the usual way. Do the residuals meet these assumptions? Discuss with a instructor.
107 |
108 | \
109 |
110 | 21\. Write a short summary in you R script (don’t forget to comment this out with `#`) describing the interpretation of this model. Report the appropriate summary statistics such as *F* values, degrees of freedom and p values.
111 |
112 | \
113 |
114 | 22\. (Optional) refit the model using the square root transformed `beat_rate` as the response variable. Does the interpretation of the model change? Do the validation plots of the residuals look better?
115 |
116 | \
117 |
118 | End of Exercise 5
--------------------------------------------------------------------------------
/exercise_6.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Exercise 6"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r setup, echo=FALSE}
9 | knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
10 | ```
11 |
12 | \
13 |
14 | ## Exercise 6: Basic programming in R
15 |
16 | \
17 |
18 | Read [Chapter 7](https://intro2r.com/prog-r.html) to help you complete the questions in this exercise.
19 |
20 | \
21 |
22 | 1\. Create a function to calculate the area of a circle. Test the function by finding the area of a circle with a diameter of 3.4 cm. Can you use it on a vector of data?
23 |
24 | \
25 |
26 | 2\. Write a function to convert farenheit to centegrade (oC = (oF - 32) x 5/9). Get your function to print out your result in the following format: "Farenheit : *value of oF* is equivalent to *value oC* centigrade."
27 |
28 | \
29 |
30 | 3\. Create a vector of normally distributed data, of length 100, mean 35 and standard deviation of 15. Write a function to calculate the mean, median, and range of the vector, print these values out with appropriate labels. Also get the function to plot a histogram (as a proportion) of the values and add a density curve.
31 |
32 | \
33 |
34 | 4\. Write a function to calculate the median value of a vector of numbers (yes I know there's a ```median()``` function already but this is fun!). Be careful with vectors of an even sample size, as you will have to take the average of the two central numbers (hint: use modulo %%2 to determine whether the vector is an odd or an even size). Test your function on vectors with both odd and even sample sizes.
35 |
36 | \
37 |
38 | 5\. You are a population ecologist for the day and wish to investigate the properties of the [Ricker model](https://en.wikipedia.org/wiki/Ricker_model). The Ricker model is defined as:
39 |
40 | \
41 |
42 |
43 | $$ N_{t+1} = N_{t} exp\left[r\left(1- \frac{N_{t}}{K} \right) \right] $$
44 |
45 | \
46 |
47 | 5\. (cont) Where *N~t~* is the population size at time *t*, *r* is the population growth rate and *K* is the carrying capacity. Write a function to simulate this model so you can conveniently determine the effect of changing *r* and the initial population size N0. *K* is often set to 100 by default, but you want the option of being able to change this with your function. So, you will need a function with the following arguments; nzero which sets the initial population size, *r* which will determine the population growth rate, time which sets how long the simulation will run for and *K* which we will initially set to 100 by default.
48 |
49 | \
50 |
51 | End of Exercise 6
--------------------------------------------------------------------------------
/exercise_6_solution.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Exercise Solutions'
3 | output:
4 | html_document:
5 | toc: false
6 | code_folding: hide
7 | ---
8 |
9 | ```{r setup, echo=FALSE, purl = FALSE}
10 | knitr::opts_chunk$set(echo=TRUE, message = FALSE, warning = FALSE, eval = FALSE, cache = FALSE)
11 | ```
12 |
13 | \
14 |
15 | ## Exercise 6: Basic programming in R
16 |
17 | \
18 |
19 | Read [Chapter 7](https://intro2r.com/prog-r.html) to help you complete the questions in this exercise.
20 |
21 | \
22 |
23 | 1\. Create a function to calculate the area of a circle. Test the function by finding the area of a circle with a diameter of 3.4 cm. Can you use it on a vector of data?
24 |
25 | ```{r Q1, results = 'asis'}
26 |
27 | # area of a circle
28 | # the equation to calculate the area of a circle is pi * radius^2
29 |
30 | circle.area <- function(d){
31 | pi * (d/2)^2
32 | }
33 |
34 | # to use your new function
35 |
36 | circle.area(10)
37 | # [1] 78.53982
38 |
39 | # to test on a vector of diameters
40 | # first create a vector with diameters ranging from 0 to 50 in steps of 10
41 |
42 | cir.diam <- seq(from = 0, to = 50, by = 10)
43 |
44 | # test your function
45 |
46 | circle.area(cir.diam)
47 | # [1] 0.00000 78.53982 314.15927 706.85835 1256.63706 1963.49541
48 | ```
49 |
50 | \
51 |
52 | 2\. Write a function to convert farenheit to centegrade (oC = (oF - 32) x 5/9). Get your function to print out your result in the following format: "Farenheit : *value of oF* is equivalent to *value oC* centigrade."
53 |
54 | ```{r Q2, tidy = TRUE}
55 |
56 | far.cent <- function(a){
57 | val <- (a-32)*5/9
58 | print(paste("Fahrenheit: ", round(a, digits = 3), "oF",sep = " "), quote = FALSE)# round 3dp
59 | print(paste("Centigrade: ", round(val, digits = 3), "oC", sep = " "), quote = FALSE)# round 3dp
60 | }
61 |
62 | # alternative Fahrenheit to centigrade using cat function
63 |
64 | far.cent2 <- function(a){
65 | val <- (a - 32) * 5/9 #calculation
66 | cat("Fahrenheit: ", round(a, digits = 3), "oF", "\n") # use cat function
67 | cat("Centigrade: ", round(val, digits = 3), "oC", "\n")
68 | }
69 | ```
70 |
71 | \
72 |
73 | 3\. Create a vector of normally distributed data, of length 100, mean 35 and standard deviation of 15. Write a function to calculate the mean, median, and range of the vector, print these values out with appropriate labels. Also get the function to plot a histogram (as a proportion) of the values and add a density curve.
74 |
75 | ```{r Q3}
76 |
77 | # Create a vector of normally distributed data
78 | # length 100, mean 35 and standard deviation of 29
79 |
80 | vals <- rnorm(100, 35, 15) # create some norm dist data mean 35, sd = 15
81 |
82 | summary.fun <- function(dat){
83 | mymean <- round(mean(dat), digits = 4) # calc mean
84 | mymedian <- round(median(dat), digits = 4) # calc median
85 | mymin <- round(min(dat), digits = 4) # calc min
86 | mymax <- round(max(dat), digits = 4) # calc max
87 | print(paste("mean:", mymean, sep = " "), quote = FALSE) # print mean
88 | print(paste("median:", mymedian, sep = " "), quote = FALSE) # print median
89 | print(paste("range:", "from:", mymin, "to", mymax, sep = " "), quote = FALSE)
90 | dens <- density(dat) # estimate density curve
91 | hist(dat, main = "",type = "l",freq = FALSE) # plot histogram
92 | lines(dens, lty = 1, col = "red") # plot density curve
93 | }
94 |
95 | # use the function
96 | summary.fun(vals)
97 | ```
98 |
99 | \
100 |
101 | 4\. Write a function to calculate the median value of a vector of numbers (yes I know there's a ```median()``` function already but this is fun!). Be careful with vectors of an even sample size, as you will have to take the average of the two central numbers (hint: use modulo %%2 to determine whether the vector is an odd or an even size). Test your function on vectors with both odd and even sample sizes.
102 |
103 | ```{r Q4}
104 |
105 | # calculate a median
106 |
107 | ourmedian <- function(x){
108 | n <- length(x)
109 | if (n %% 2 == 1) # odd numbers
110 | sort(x)[(n + 1)/2] # find the middle number by adding 1 to length and div 2
111 | else { # even numbers
112 | middletwo <- sort(x)[(n/2) + 0:1] #find the two middle numbers
113 | mean(middletwo)
114 | }
115 | }
116 |
117 | # use the function
118 | mydat <- sample(1:50, size = 10, replace = TRUE )
119 |
120 | # our function
121 | ourmedian(mydat)
122 |
123 | # R median function
124 | median(mydat)
125 | ```
126 |
127 | \
128 |
129 | 5\. You are a population ecologist for the day and wish to investigate the properties of the [Ricker model](https://en.wikipedia.org/wiki/Ricker_model). The Ricker model is defined as:
130 |
131 | \
132 |
133 |
134 | $$ N_{t+1} = N_{t} exp\left[r\left(1- \frac{N_{t}}{K} \right) \right] $$
135 |
136 | \
137 |
138 | 5\. (cont) Where *N~t~* is the population size at time *t*, *r* is the population growth rate and *K* is the carrying capacity. Write a function to simulate this model so you can conveniently determine the effect of changing *r* and the initial population size N0. *K* is often set to 100 by default, but you want the option of being able to change this with your function. So, you will need a function with the following arguments; nzero which sets the initial population size, *r* which will determine the population growth rate, time which sets how long the simulation will run for and *K* which we will initially set to 100 by default.
139 |
140 | ```{r Q5, tidy = TRUE}
141 |
142 | # function to simulate Ricker model
143 |
144 | Ricker.model <- function(nzero, r, time, K=1){ # sets initial parameters
145 | N <- numeric(time + 1) # creates a real vector of length time+1 to store values of Nt+1
146 | N[1] <- nzero # sets initial population size in first element of N
147 | for (i in 1:time) { # loops over time
148 | N[i+1] <- N[i]*exp(r*(1 - N[i]/K))
149 | }
150 | Time <- 0:time # creates vector for x axis
151 | plot(Time, N, type = "o", xlim = c(0, time), xlab = "Time", ylab = "Population size (N)", main = paste("r =", r, sep=" ")) # plots output
152 | }
153 |
154 | # To run
155 | # play around with the different parameters, especially r
156 | Ricker.model(nzero=0.1,r=1,time=100)
157 | ```
158 |
159 | \
160 |
161 | End of Exercise 6
--------------------------------------------------------------------------------
/exercise_pdf.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "PDF version of exercises"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r, include=FALSE}
9 | library(knitr)
10 | library(stringr)
11 | knitr::opts_chunk$set(message=FALSE, warning=FALSE, eval=TRUE, echo=FALSE)
12 | suppressPackageStartupMessages(library(dplyr))
13 | suppressPackageStartupMessages(library(stringr))
14 | source('reveal.R')
15 | ```
16 |
17 | \
18 |
19 | Click on the links below to download pdf versions of the exercises.
20 |
21 | \
22 |
23 | ```{r, reveal, echo=FALSE, eval = isFALSE(show_exercise)}
24 | cat("Exercises will be released as the course progresses")
25 | ```
26 |
27 | \
28 |
29 | ```{r, results='asis', eval = isTRUE(show_exercise)}
30 | ex_text <- c(": Getting to know R and RStudio", ": Basic R operations",
31 | ": Importing and manipulating dataframes",
32 | ": Visualising data using base R and lattice graphics",
33 | ": Basic statistics in R",
34 | ": Basic programming in R")
35 |
36 | dir <- "exercises"
37 | file_name <- list.files(dir) %>%
38 | sort %>%
39 | grep("[*.zip]", ., value=TRUE)
40 |
41 | link_name <- file_name %>%
42 | gsub("\\.pdf", "", .) %>%
43 | gsub("_", " ", .) %>%
44 | str_to_sentence(.)
45 |
46 | paste0("- [", link_name, ex_text, "](", "exercises/", file_name, "){target='_blank'}") %>%
47 | cat(sep="\n\n")
48 |
49 | ```
50 |
--------------------------------------------------------------------------------
/exercise_solutions.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Exercise Solutions"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r, include=FALSE}
9 | library(knitr)
10 | library(stringr)
11 | knitr::opts_chunk$set(message=FALSE, warning=FALSE, eval=TRUE, echo=FALSE)
12 | suppressPackageStartupMessages(library(dplyr))
13 | suppressPackageStartupMessages(library(stringr))
14 | source('reveal.R')
15 | ```
16 |
17 | \
18 |
19 | Follow the links below for solutions to each of the exercises you have completed on this course. Click on the 'code' buttons to reveal the R code associated with each question. If you would prefer these solutions as R scripts for later offline use then you can [find these here](course_code.html).
20 |
21 | \
22 |
23 | ```{r, reveal, echo=FALSE, eval = isFALSE(show_text12)}
24 | cat("solutions will be released as the course progresses")
25 | ```
26 |
27 | ```{r sol12, results='asis', eval = isTRUE(show_text12)}
28 | file_name <- list.files('.') %>%
29 | sort %>%
30 | grep("(exercise_[12]_solution.html)", . , value=TRUE)
31 |
32 | link_name <- file_name %>%
33 | gsub("\\.html", "", .) %>%
34 | paste0(., "s") %>%
35 | gsub("_", " ", .) %>%
36 | str_to_sentence(.)
37 |
38 | paste0("- [", link_name, "](", file_name, "){target='_blank'}") %>%
39 | cat(sep="\n\n")
40 | ```
41 |
42 |
43 | ```{r sol34, results='asis', eval = isTRUE(show_text34)}
44 | file_name <- list.files('.') %>%
45 | sort %>%
46 | grep("(exercise_[34]_solution.html|exercise_[34]_ggplot_solution.html)", . , value=TRUE) %>%
47 | .[c(1,3,2)]
48 |
49 | link_name <- file_name %>%
50 | gsub("\\.html", "", .) %>%
51 | paste0(., "s") %>%
52 | gsub("_", " ", .) %>%
53 | str_to_sentence(.)
54 |
55 | paste0("- [", link_name, "](", file_name, "){target='_blank'}") %>%
56 | cat(sep="\n\n")
57 | ```
58 |
59 | ```{r sol56, results='asis', eval = isTRUE(show_text56)}
60 | file_name <- list.files('.') %>%
61 | sort %>%
62 | grep("(exercise_[56]_solution.html)", . , value=TRUE)
63 |
64 | link_name <- file_name %>%
65 | gsub("\\.html", "", .) %>%
66 | paste0(., "s") %>%
67 | gsub("_", " ", .) %>%
68 | str_to_sentence(.)
69 |
70 | paste0("- [", link_name, "](", file_name, "){target='_blank'}") %>%
71 | cat(sep="\n\n")
72 | ```
73 |
74 | \
75 |
76 | [Offline R scripts](course_code.html)
77 |
78 | ```{r, include = FALSE}
79 | # TODO: generate list automagically
80 | knitr::purl('./exercise_1_solution.Rmd', output = './exercise_solutions/exercise_1_solution.R', quiet = TRUE)
81 | knitr::purl('./exercise_2_solution.Rmd', output = './exercise_solutions/exercise_2_solution.R', quiet = TRUE)
82 | knitr::purl('./exercise_3_solution.Rmd', output = './exercise_solutions/exercise_3_solution.R', quiet = TRUE)
83 | knitr::purl('./exercise_4_solution.Rmd', output = './exercise_solutions/exercise_4_solution.R', quiet = TRUE)
84 | knitr::purl('./exercise_4_ggplot_solution.Rmd', output = './exercise_solutions/exercise_4_ggplot_solution.R', quiet = TRUE)
85 | knitr::purl('./exercise_5_solution.Rmd', output = './exercise_solutions/exercise_5_solution.R', quiet = TRUE)
86 | knitr::purl('./exercise_6_solution.Rmd', output = './exercise_solutions/exercise_6_solution.R', quiet = TRUE)
87 | ```
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/exercise_solutions/exercise_1_solution.R:
--------------------------------------------------------------------------------
1 | ## ----Q4-----------------------------------------------------------------------------------------------
2 | help(mean) # different methods of using help
3 | ?mean
4 | help("mean")
5 |
6 |
7 | ## ----Q5-----------------------------------------------------------------------------------------------
8 | plot(1:10) #dont worry about what 1:10 does just yet
9 |
10 |
11 | ## ----Q6-----------------------------------------------------------------------------------------------
12 | first_num <- 42 # create variable first_num and assign the value 42
13 | first_char <- "my first character"
14 |
15 |
16 | ## ----Q7-----------------------------------------------------------------------------------------------
17 | rm(first_num)
18 | ls() # list all variables in the workspace
19 |
20 |
21 | ## ----Q8-----------------------------------------------------------------------------------------------
22 | first_char <- "my second variable"
23 | first_char # display the value
24 |
25 |
26 | ## ----Q11----------------------------------------------------------------------------------------------
27 | apropos("plot")
28 | help('plot.design')
29 |
30 |
31 | ## ----Q12----------------------------------------------------------------------------------------------
32 | help.search("plot")
33 | ??plot # shortcut for help.search function
34 |
35 | help.search("plot", package = "nlme")
36 |
37 |
38 | ## ----Q13----------------------------------------------------------------------------------------------
39 | getwd() # displays the current working directory
40 |
41 |
42 | ## ----Q14----------------------------------------------------------------------------------------------
43 | dir.create(path = 'data')
44 | dir.create(path = 'output')
45 | list.files(include.dirs = TRUE)
46 |
47 |
--------------------------------------------------------------------------------
/exercise_solutions/exercise_2_solution.R:
--------------------------------------------------------------------------------
1 | ## ----Q2, results = 'asis'-----------------------------------------------------------------------------
2 | log(12.43) # natural log
3 | log10(12.43) # log to base 10
4 | log2(12.43) # log to base 2
5 | log(12.43, base = 2) # alternative log to base 2
6 | sqrt(12.43) # square root
7 | exp(12.43) # exponent
8 |
9 |
10 | ## ----Q3, results = 'asis'-----------------------------------------------------------------------------
11 | area_circle <- pi * (20/2)^2
12 |
13 |
14 | ## ----Q4-----------------------------------------------------------------------------------------------
15 | (14 * 0.51)^(1/3)
16 |
17 |
18 | ## ----Q5-----------------------------------------------------------------------------------------------
19 | weight <- c(69, 62, 57, 59, 59, 64, 56, 66, 67, 66)
20 |
21 |
22 | ## ----Q6, results = 'asis'-----------------------------------------------------------------------------
23 | mean(weight) # calculate mean
24 | var(weight) # calculate variance
25 | sd(weight) # calculate standard deviation
26 | range(weight) # range of weight values
27 | length(weight) # number of observations
28 |
29 | first_five <- weights[1:5] # extract first 5 weight values
30 | first_five <- weights[c(1, 2, 3, 4, 5)] # alternative method
31 |
32 |
33 | ## ----Q7, results = 'asis'-----------------------------------------------------------------------------
34 | height <- c(112, 102, 83, 84, 99, 90, 77, 112, 133, 112)
35 |
36 | summary(height) # summary statistics of height variable
37 |
38 | some_child <- height[c(2, 3, 9, 10)] # extract the 2nd, 3rd, 9th, 10th height
39 |
40 | shorter_child <- height[height <= 99] # extract all heights less than or equal to 99
41 |
42 |
43 | ## ----Q8-----------------------------------------------------------------------------------------------
44 | bmi <- weight/(height/100)^2 # don't forget to convert height to meters
45 |
46 |
47 | ## ----Q9-----------------------------------------------------------------------------------------------
48 | seq1 <- seq(from = 0, to = 1, by = 0.1)
49 |
50 |
51 | ## ----Q10----------------------------------------------------------------------------------------------
52 | seq2 <- rev(seq(from = 1, to = 10, by = 0.5))
53 |
54 |
55 | ## ----Q11----------------------------------------------------------------------------------------------
56 | rep(1:3, times = 3)
57 | rep(c("a", "c", "e", "g"), each = 3)
58 | rep(c("a", "c", "e", "g"), times = 3)
59 | rep(1:3, each = 3, times = 2)
60 | rep(1:5, times = 5:1)
61 | rep(c(7, 2, 8, 1), times = c(4, 3, 1, 5))
62 |
63 |
64 | ## ----Q12----------------------------------------------------------------------------------------------
65 | height_sorted <- sort(height)
66 |
67 | height_rev <- rev(sort(height))
68 |
69 |
70 |
71 | ## ----Q13----------------------------------------------------------------------------------------------
72 | child_name <- c("Alfred", "Barbara", "James", "Jane", "John", "Judy", "Louise", "Mary", "Ronald", "William")
73 |
74 |
75 | ## ----Q14----------------------------------------------------------------------------------------------
76 | height_ord <- order(height) # get the indexes of the heights, smallest to tallest
77 | names_sort <- child_name[height_ord] # Louise is shortest, Ronald is tallest
78 |
79 |
80 | ## ----Q15----------------------------------------------------------------------------------------------
81 | weight_ord <- rev(order(weight))
82 | weight_rev <- child_name[weight_ord] # Alfred is heaviest, Louise is lightest
83 |
84 |
85 | ## ----Q16----------------------------------------------------------------------------------------------
86 | mydata <- c(2, 4, 1, 6, 8, 5, NA, 4, 7)
87 | mean(mydata) # returns NA!
88 |
89 | mean(mydata, na.rm = TRUE) # returns 4.625
90 |
91 |
92 | ## ----Q17----------------------------------------------------------------------------------------------
93 | ls() # list all variables in workspace
94 | rm(seq1) # remove variable seq1 from the workspace
95 | ls() # check seq1 has been removed
96 |
97 |
--------------------------------------------------------------------------------
/exercise_solutions/exercise_3_solution.R:
--------------------------------------------------------------------------------
1 | ## ----Q5-----------------------------------------------------------------------------------------------
2 | whale <- read.table('data/whaledata.txt', header = TRUE,
3 | stringsAsFactors = TRUE)
4 |
5 |
6 | ## ----Q6, results = 'asis'-----------------------------------------------------------------------------
7 | head(whale) # display the first 5 rows
8 | names(whale) # display the variable names
9 | str(whale) # display the structure of the dataframe whale
10 |
11 | # 'data.frame': 100 obs. of 8 variables:
12 | # $ month : Factor w/ 2 levels "May","October": 1 1 1 1 ...
13 | # $ time.at.station: int 1344 1633 743 1050 1764 580 459 ...
14 | # $ water.noise : Factor w/ 3 levels "high","low","medium": 2 3 3 3 ...
15 | # $ number.whales : int 7 13 12 10 12 10 5 8 11 12 ...
16 | # $ latitude : num 60.4 60.4 60.5 60.3 60.4 ...
17 | # $ longitude : num -4.18 -4.19 -4.62 -4.35 -5.2 ...
18 | # $ depth : int 520 559 1006 540 1000 1000 993 988 ...
19 | # $ gradient : int 415 405 88 409 97 173 162 162 245 161 ..
20 |
21 | # the dataframe whale has 100 observations
22 | # the dataframe whale has 8 variables
23 | # the variables month and water.noise are factors
24 |
25 |
26 | ## ----Q7, results = 'asis'-----------------------------------------------------------------------------
27 | summary(whale)
28 |
29 | # NOTE: I have removed the last 3 column information to save space!
30 |
31 | # month time.at.station water.noise number.whales latitude
32 | # May :50 Min. : 60.0 high :15 Min. : 0.00 Min. :60.29
33 | # October:50 1st Qu.: 693.8 low :28 1st Qu.: 9.00 1st Qu.:60.69
34 | # Median :1077.5 medium:57 Median :11.00 Median :61.29
35 | # Mean :1064.7 Mean :11.56 Mean :61.16
36 | # 3rd Qu.:1349.2 3rd Qu.:14.00 3rd Qu.:61.59
37 | # Max. :2158.0 Max. :28.00 Max. :62.10
38 | # NA's :1
39 |
40 | # the variable number.whales has one missing value (NA)
41 |
42 |
43 | ## ----Q8, results = 'asis'-----------------------------------------------------------------------------
44 | # first 10 rows and first 4 columns
45 | whale.sub <- whale[1:10, 1:4]
46 |
47 | # all rows and columns 1, 3 and 6
48 | whale.num <- whale[, c(1, 3, 4)]
49 | # alternative way of indexing columns with named indexes
50 | whale.num <- whale[, c("month", "water.noise", "number.whales")]
51 |
52 | # first 50 rows and all columns
53 | whale.may <- whale[1:50, ]
54 |
55 | # excluding first 10 rows and last column using negative indexing
56 | whale.last <- whale[-c(1:10), -8]
57 | # more general way if you have lots of columns
58 | whale.last <- whale[-c(1:10), -c(ncol(whale))]
59 | # NOTE: this doesn't work for named columns
60 | whale.last <- whale[-c(1:10), -c("gradient")]
61 |
62 |
63 | ## ----Q9, tidy = TRUE----------------------------------------------------------------------------------
64 | whale.1200 <- whale[whale$depth > 1200, ]
65 |
66 | whale.200 <- whale[whale$gradient > 200, ]
67 |
68 | whale.low <- whale[whale$water.noise == 'low', ]
69 |
70 | whale.h.may <- whale[whale$water.noise == 'high' & whale$month == 'May', ]
71 |
72 | whale.subset <- whale[whale$month == 'October' & whale$water.noise == 'low' & whale$gradient > 132, ]
73 |
74 | whale.lat.long <- whale[whale$latitude > 60 & whale$latitude < 61 & whale$longitude > -6 & whale$longitude < -4, ]
75 |
76 | whale.nomed <- whale[whale$water.noise != 'medium', ]
77 |
78 |
79 | ## ----Q10, tidy = TRUE---------------------------------------------------------------------------------
80 | whale.subset <- whale[whale$month == 'October' & whale$water.noise == 'low' & whale$gradient > median(whale$gradient), ]
81 |
82 |
83 | ## ----Q11, tidy = TRUE---------------------------------------------------------------------------------
84 | # results in a dataframe filled with NAs.
85 | whale.new <- whale[whale$depth > 1500 & whale$number.whales > mean(whale$number.whales), ]
86 |
87 | # the variable number.whales contains 1 NA value. By default the mean function will return an NA.
88 | # use the na.rm argument to ignore NAs
89 | whale.new <- whale[whale$depth > 1500 & whale$number.whales > mean(whale$number.whales, na.rm = TRUE), ]
90 |
91 |
92 |
93 | ## ----Q12, tidy = TRUE---------------------------------------------------------------------------------
94 | subset(whale, month == 'May' & time.at.station < 1000 & depth > 1000)
95 |
96 | subset(whale, month == "October" & latitude > 61, select = c("month", "latitude", "longitude", "number.whales"))
97 |
98 |
99 | ## ----Q13----------------------------------------------------------------------------------------------
100 | whale.depth.sort <- whale[order(whale$depth), ]
101 |
102 |
103 | ## ----Q14, results = 'asis'----------------------------------------------------------------------------
104 | # notice how the variable water.noise has been ordered - why?
105 | whale.sorted <- whale[order(whale$water.noise, whale$depth), ]
106 |
107 | # use '-' to reverse the order of depth
108 | whale.rev.sorted <- whale[order(whale$water.noise, -whale$depth), ]
109 |
110 |
111 | ## ----Q15a---------------------------------------------------------------------------------------------
112 | mean(whale$time.at.station) # mean time at station
113 | median(whale$depth) # median depth
114 | length(whale$number.whales) # number of observations
115 |
116 |
117 | ## ----Q15b, results = 'asis'---------------------------------------------------------------------------
118 | tapply(whale$number.whales, whale$water.noise, mean) # notice the NA?
119 |
120 | # use the na.rm argument again
121 | tapply(whale$number.whales, whale$water.noise, mean, na.rm = TRUE)
122 |
123 | # alternative method using the with() function. see ?with
124 | with(whale, tapply(number.whales, water.noise, mean, na.rm = TRUE))
125 |
126 | # when using multiple factors these need to be supplied as a list
127 | tapply(whale$number.whales, list(whale$water.noise, whale$month), median, na.rm = TRUE)
128 |
129 |
130 |
131 | ## ----Q16, tidy = TRUE---------------------------------------------------------------------------------
132 | aggregate(whale[, c(2, 4, 7, 8)], by = list(water.noise = whale$water.noise), mean, na.rm = TRUE)
133 |
134 | aggregate(whale[, c(2, 4, 7, 8)], by = list(water.noise = whale$water.noise, month = whale$month), mean, na.rm = TRUE)
135 |
136 | # optional question. Need to specify a function 'on the fly' using function(x){}
137 | aggregate(whale[, c(2, 4, 7, 8)], by = list(water.noise = whale$water.noise, month = whale$month), function(x){round(mean(x, na.rm = TRUE), digits = 2)})
138 |
139 |
140 | ## ----Q17, results = 'asis'----------------------------------------------------------------------------
141 | # using table
142 | table(whale$water.noise)
143 | table(whale$water.noise, whale$month)
144 |
145 | # using xtabs
146 | xtabs(~ water.noise, data = whale)
147 | xtabs(~ month + water.noise, data = whale)
148 |
149 |
150 | ## ----Q18, eval=FALSE, tidy = TRUE---------------------------------------------------------------------
151 | ## write.table(whale.num, "output/whale_num.txt", col.names = TRUE, row.names = FALSE, sep = "\t")
152 |
153 |
--------------------------------------------------------------------------------
/exercise_solutions/exercise_4_ggplot_solution.R:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/exercise_solutions/exercise_6_solution.R:
--------------------------------------------------------------------------------
1 | ## ----Q1, results = 'asis'-----------------------------------------------------------------------------
2 |
3 | # area of a circle
4 | # the equation to calculate the area of a circle is pi * radius^2
5 |
6 | circle.area <- function(d){
7 | pi * (d/2)^2
8 | }
9 |
10 | # to use your new function
11 |
12 | circle.area(10)
13 | # [1] 78.53982
14 |
15 | # to test on a vector of diameters
16 | # first create a vector with diameters ranging from 0 to 50 in steps of 10
17 |
18 | cir.diam <- seq(from = 0, to = 50, by = 10)
19 |
20 | # test your function
21 |
22 | circle.area(cir.diam)
23 | # [1] 0.00000 78.53982 314.15927 706.85835 1256.63706 1963.49541
24 |
25 |
26 | ## ----Q2, tidy = TRUE----------------------------------------------------------------------------------
27 |
28 | far.cent <- function(a){
29 | val <- (a-32)*5/9
30 | print(paste("Fahrenheit: ", round(a, digits = 3), "oF",sep = " "), quote = FALSE)# round 3dp
31 | print(paste("Centigrade: ", round(val, digits = 3), "oC", sep = " "), quote = FALSE)# round 3dp
32 | }
33 |
34 | # alternative Fahrenheit to centigrade using cat function
35 |
36 | far.cent2 <- function(a){
37 | val <- (a - 32) * 5/9 #calculation
38 | cat("Fahrenheit: ", round(a, digits = 3), "oF", "\n") # use cat function
39 | cat("Centigrade: ", round(val, digits = 3), "oC", "\n")
40 | }
41 |
42 |
43 | ## ----Q3-----------------------------------------------------------------------------------------------
44 |
45 | # Create a vector of normally distributed data
46 | # length 100, mean 35 and standard deviation of 29
47 |
48 | vals <- rnorm(100, 35, 15) # create some norm dist data mean 35, sd = 15
49 |
50 | summary.fun <- function(dat){
51 | mymean <- round(mean(dat), digits = 4) # calc mean
52 | mymedian <- round(median(dat), digits = 4) # calc median
53 | mymin <- round(min(dat), digits = 4) # calc min
54 | mymax <- round(max(dat), digits = 4) # calc max
55 | print(paste("mean:", mymean, sep = " "), quote = FALSE) # print mean
56 | print(paste("median:", mymedian, sep = " "), quote = FALSE) # print median
57 | print(paste("range:", "from:", mymin, "to", mymax, sep = " "), quote = FALSE)
58 | dens <- density(dat) # estimate density curve
59 | hist(dat, main = "",type = "l",freq = FALSE) # plot histogram
60 | lines(dens, lty = 1, col = "red") # plot density curve
61 | }
62 |
63 | # use the function
64 | summary.fun(vals)
65 |
66 |
67 | ## ----Q4-----------------------------------------------------------------------------------------------
68 |
69 | # calculate a median
70 |
71 | ourmedian <- function(x){
72 | n <- length(x)
73 | if (n %% 2 == 1) # odd numbers
74 | sort(x)[(n + 1)/2] # find the middle number by adding 1 to length and div 2
75 | else { # even numbers
76 | middletwo <- sort(x)[(n/2) + 0:1] #find the two middle numbers
77 | mean(middletwo)
78 | }
79 | }
80 |
81 | # use the function
82 | mydat <- sample(1:50, size = 10, replace = TRUE )
83 |
84 | # our function
85 | ourmedian(mydat)
86 |
87 | # R median function
88 | median(mydat)
89 |
90 |
91 | ## ----Q5, tidy = TRUE----------------------------------------------------------------------------------
92 |
93 | # function to simulate Ricker model
94 |
95 | Ricker.model <- function(nzero, r, time, K=1){ # sets initial parameters
96 | N <- numeric(time + 1) # creates a real vector of length time+1 to store values of Nt+1
97 | N[1] <- nzero # sets initial population size in first element of N
98 | for (i in 1:time) { # loops over time
99 | N[i+1] <- N[i]*exp(r*(1 - N[i]/K))
100 | }
101 | Time <- 0:time # creates vector for x axis
102 | plot(Time, N, type = "o", xlim = c(0, time), xlab = "Time", ylab = "Population size (N)", main = paste("r =", r, sep=" ")) # plots output
103 | }
104 |
105 | # To run
106 | # play around with the different parameters, especially r
107 | Ricker.model(nzero=0.1,r=1,time=100)
108 |
109 |
--------------------------------------------------------------------------------
/exercises.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Exercises'
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | ```{r, include=FALSE}
9 | library(knitr)
10 | library(stringr)
11 | knitr::opts_chunk$set(message=FALSE, warning=FALSE, eval=TRUE, echo=FALSE)
12 | suppressPackageStartupMessages(library(dplyr))
13 | suppressPackageStartupMessages(library(stringr))
14 | source('reveal.R')
15 | ```
16 |
17 | \
18 |
19 | ### Exercises
20 |
21 | The following exercises will test your understanding of the material covered during this course. Each exercise corresponds to material covered in each section of the Introduction to R manual. It’s entirely up to you how you progress through these exercises, everyone learns at their own pace and in their own way. You can either work your way through each section of the manual and then test your understanding of the material by completing the associated exercise. Alternatively, you can start with each exercise and refer back to the appropriate material in the manual. Or find another way that works for you. Whichever approach you use, make sure that you write your R code in RStudio (or your favourite script editor), annotate it liberally and save it regularly. At the end of the course you will have many hundreds of lines of code that you can refer back to at a later date when you’ve forgotten most of it! I will release the [solutions to the exercises](exercise_solutions.html){target="_blank"} as the course progresses. If you prefer to download these exercises in pdf format you can [find them here](exercise_pdf.html){target="_blank"}.
22 |
23 | Finally, just a word about the content of the exercises. Initially, some of the material in the exercises might strike you as ‘pointless’, ‘trivial’ or ‘irrelevant’ and you may even ask yourself what possible use is generating sequences of numbers, concatenating elements in a vector or ordering lists of names (to name but a few). However, please stick with it, you’ll be amazed how many times you will use the skills (and code) that you have learned throughout these exercises when it comes to dealing with and analysing your own data.
24 |
25 | Have fun!
26 |
27 | \
28 |
29 |
30 | ```{r, reveal, echo=FALSE, eval = isFALSE(show_exercise)}
31 | cat("Exercises will be released as the course progresses")
32 | ```
33 |
34 | \
35 |
36 | ```{r, results='asis', eval = isTRUE(show_exercise)}
37 | ex_text <- c(": Getting to know R and RStudio", ": Basic R operations",
38 | ": Importing and manipulating dataframes",
39 | ": Visualising data using base R and lattice graphics",
40 | ": Basic statistics in R",
41 | ": Basic programming in R")
42 |
43 | file_name <- list.files('.') %>%
44 | sort %>%
45 | grep("exercise_[0-9].html", . , value=TRUE)
46 |
47 | link_name <- file_name %>%
48 | gsub("\\.html", "", .) %>%
49 | gsub("_", " ", .) %>%
50 | str_to_sentence(.)
51 |
52 | paste0("- [", link_name, ex_text, "](", file_name, "){target='_blank'}") %>%
53 | cat(sep="\n\n")
54 | ```
55 |
56 | \
57 |
58 | ```{r, include = FALSE}
59 | # TODO: generate list automagically
60 | rmarkdown::render("exercise_1.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_1.pdf", quiet = TRUE)
61 | rmarkdown::render("exercise_2.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_2.pdf", quiet = TRUE)
62 | rmarkdown::render("exercise_3.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_3.pdf", quiet = TRUE)
63 | rmarkdown::render("exercise_4.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_4.pdf", quiet = TRUE)
64 | rmarkdown::render("exercise_5.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_5.pdf", quiet = TRUE)
65 | rmarkdown::render("exercise_6.Rmd", output_format = "pdf_document", output_file = "./exercises/exercise_6.pdf", quiet = TRUE)
66 |
67 | ```
68 |
69 | [pdf version of exercises](exercise_pdf.html)
70 |
71 | [Exercise solutions](exercise_solutions.html)
72 |
--------------------------------------------------------------------------------
/exercises/exercise_1.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_1.pdf
--------------------------------------------------------------------------------
/exercises/exercise_2.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_2.pdf
--------------------------------------------------------------------------------
/exercises/exercise_3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_3.pdf
--------------------------------------------------------------------------------
/exercises/exercise_4.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_4.pdf
--------------------------------------------------------------------------------
/exercises/exercise_5.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_5.pdf
--------------------------------------------------------------------------------
/exercises/exercise_6.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/exercises/exercise_6.pdf
--------------------------------------------------------------------------------
/figs/simple-ggplot-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/figs/simple-ggplot-1.png
--------------------------------------------------------------------------------
/figs/simple-plot-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/figs/simple-plot-1.png
--------------------------------------------------------------------------------
/figs/simple-plot-cap-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/figs/simple-plot-cap-1.png
--------------------------------------------------------------------------------
/figs/simple-plot2-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/figs/simple-plot2-1.png
--------------------------------------------------------------------------------
/figs/simple-plot3-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/figs/simple-plot3-1.png
--------------------------------------------------------------------------------
/howto.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'How-to'
3 | output:
4 | html_document:
5 | css: custom.css
6 | toc: no
7 | ---
8 | ```{r, include=FALSE}
9 | library(htmltools)
10 | suppressPackageStartupMessages(library(htmltools))
11 | source('utils.R')
12 | source('reveal.R')
13 | ```
14 |
15 | \
16 |
17 | Short how-to videos to get you started with some important topics.
18 |
19 | \
20 |
21 | ## Installing R and RStudio {#install-vid}
22 |
23 |
24 |
25 | \
26 |
27 | ## RStudio orientation {#rstudio-vid}
28 |
29 |
30 |
31 | \
32 |
33 | ## RStudio Projects {#rstudio_proj-vid}
34 |
35 |
36 |
37 | \
38 |
39 | ## Using functions {#func-vid}
40 |
41 |
42 |
43 | \
44 |
45 | ## Objects in R {#objs-vid}
46 |
47 |
48 |
49 | \
50 |
51 | ## Creating vectors in R {#vec-vid}
52 |
53 |
54 |
55 | \
56 |
57 | ## Working with vectors in R {#vec2-vid}
58 |
59 |
60 |
61 | \
62 |
63 | ## Installing packages in R {#pack-vid}
64 |
65 |
66 |
67 | \
68 |
69 | ## Data frames in R {#dataf-vid}
70 |
71 |
72 |
73 | \
74 |
75 | ## Importing data in R {#import-vid}
76 |
77 |
78 |
79 | \
80 |
81 | ## Data wrangling using R {#dataw-vid}
82 |
83 |
84 |
85 | \
86 |
87 |
88 |
--------------------------------------------------------------------------------
/images/Clone.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Clone.PNG
--------------------------------------------------------------------------------
/images/Cute_grey_kitten.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Cute_grey_kitten.jpg
--------------------------------------------------------------------------------
/images/Deon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Deon.png
--------------------------------------------------------------------------------
/images/Diff.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Diff.png
--------------------------------------------------------------------------------
/images/FirstCommit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/FirstCommit.png
--------------------------------------------------------------------------------
/images/GitHub_Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/GitHub_Logo.png
--------------------------------------------------------------------------------
/images/GitTab.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/GitTab.png
--------------------------------------------------------------------------------
/images/Github_cartoon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Github_cartoon.png
--------------------------------------------------------------------------------
/images/Github_cartoon2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Github_cartoon2.png
--------------------------------------------------------------------------------
/images/Messy_folder.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Messy_folder.PNG
--------------------------------------------------------------------------------
/images/NewRepo3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/NewRepo3.png
--------------------------------------------------------------------------------
/images/NewRepo4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/NewRepo4.png
--------------------------------------------------------------------------------
/images/PullMaster.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/PullMaster.png
--------------------------------------------------------------------------------
/images/PushMsg.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/PushMsg.PNG
--------------------------------------------------------------------------------
/images/READMEfile.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/READMEfile.png
--------------------------------------------------------------------------------
/images/Rmarkdown_console.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Rmarkdown_console.png
--------------------------------------------------------------------------------
/images/Shell.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Shell.png
--------------------------------------------------------------------------------
/images/Thomas.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/Thomas.jpg
--------------------------------------------------------------------------------
/images/after_rcode.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/after_rcode.png
--------------------------------------------------------------------------------
/images/alex.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/alex.JPG
--------------------------------------------------------------------------------
/images/alex.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/alex.png
--------------------------------------------------------------------------------
/images/ana.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/ana.png
--------------------------------------------------------------------------------
/images/before_rcode.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/before_rcode.png
--------------------------------------------------------------------------------
/images/c_history.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/c_history.png
--------------------------------------------------------------------------------
/images/c_history2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/c_history2.png
--------------------------------------------------------------------------------
/images/c_history3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/c_history3.png
--------------------------------------------------------------------------------
/images/c_history4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/c_history4.png
--------------------------------------------------------------------------------
/images/c_history5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/c_history5.png
--------------------------------------------------------------------------------
/images/class_of_2019.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/class_of_2019.jpg
--------------------------------------------------------------------------------
/images/coffee.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/coffee.png
--------------------------------------------------------------------------------
/images/create_rm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/create_rm.png
--------------------------------------------------------------------------------
/images/data_in_r_thumb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/data_in_r_thumb.png
--------------------------------------------------------------------------------
/images/dir_struct.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/dir_struct.png
--------------------------------------------------------------------------------
/images/dir_struct2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/dir_struct2.png
--------------------------------------------------------------------------------
/images/dir_struct3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/dir_struct3.png
--------------------------------------------------------------------------------
/images/eat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/eat.png
--------------------------------------------------------------------------------
/images/final_doc.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/final_doc.gif
--------------------------------------------------------------------------------
/images/first_Rmd.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd.png
--------------------------------------------------------------------------------
/images/first_Rmd0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd0.png
--------------------------------------------------------------------------------
/images/first_Rmd2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd2.png
--------------------------------------------------------------------------------
/images/first_Rmd3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd3.png
--------------------------------------------------------------------------------
/images/first_Rmd4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd4.png
--------------------------------------------------------------------------------
/images/first_Rmd5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd5.png
--------------------------------------------------------------------------------
/images/first_Rmd6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd6.png
--------------------------------------------------------------------------------
/images/first_Rmd7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd7.png
--------------------------------------------------------------------------------
/images/first_Rmd8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/first_Rmd8.png
--------------------------------------------------------------------------------
/images/git-history.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/git-history.png
--------------------------------------------------------------------------------
/images/git_path.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/git_path.png
--------------------------------------------------------------------------------
/images/git_version.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/git_version.png
--------------------------------------------------------------------------------
/images/github.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/github.png
--------------------------------------------------------------------------------
/images/hex-rmarkdown.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/hex-rmarkdown.png
--------------------------------------------------------------------------------
/images/html_rendered.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/html_rendered.png
--------------------------------------------------------------------------------
/images/knit_rm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/knit_rm.png
--------------------------------------------------------------------------------
/images/lightbulb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/lightbulb.png
--------------------------------------------------------------------------------
/images/mod1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod1.png
--------------------------------------------------------------------------------
/images/mod2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod2.png
--------------------------------------------------------------------------------
/images/mod3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod3.png
--------------------------------------------------------------------------------
/images/mod4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod4.png
--------------------------------------------------------------------------------
/images/mod5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod5.png
--------------------------------------------------------------------------------
/images/mod6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/mod6.png
--------------------------------------------------------------------------------
/images/new_file_rm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_file_rm.png
--------------------------------------------------------------------------------
/images/new_prog_RS9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_prog_RS9.png
--------------------------------------------------------------------------------
/images/new_proj.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj.png
--------------------------------------------------------------------------------
/images/new_proj1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj1.png
--------------------------------------------------------------------------------
/images/new_proj2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj2.png
--------------------------------------------------------------------------------
/images/new_proj3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj3.png
--------------------------------------------------------------------------------
/images/new_proj4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj4.png
--------------------------------------------------------------------------------
/images/new_proj5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj5.png
--------------------------------------------------------------------------------
/images/new_proj_RS1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS1.png
--------------------------------------------------------------------------------
/images/new_proj_RS10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS10.png
--------------------------------------------------------------------------------
/images/new_proj_RS11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS11.png
--------------------------------------------------------------------------------
/images/new_proj_RS12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS12.png
--------------------------------------------------------------------------------
/images/new_proj_RS2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS2.png
--------------------------------------------------------------------------------
/images/new_proj_RS3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS3.png
--------------------------------------------------------------------------------
/images/new_proj_RS4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS4.png
--------------------------------------------------------------------------------
/images/new_proj_RS5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS5.png
--------------------------------------------------------------------------------
/images/new_proj_RS6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS6.png
--------------------------------------------------------------------------------
/images/new_proj_RS7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS7.png
--------------------------------------------------------------------------------
/images/new_proj_RS8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_proj_RS8.png
--------------------------------------------------------------------------------
/images/new_repo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_repo.png
--------------------------------------------------------------------------------
/images/new_repo_clone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_repo_clone.png
--------------------------------------------------------------------------------
/images/new_repo_opt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_repo_opt.png
--------------------------------------------------------------------------------
/images/new_rm.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_rm.png
--------------------------------------------------------------------------------
/images/new_rm2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/new_rm2.png
--------------------------------------------------------------------------------
/images/proj_setup1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/proj_setup1.png
--------------------------------------------------------------------------------
/images/proj_setup2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/proj_setup2.png
--------------------------------------------------------------------------------
/images/proj_setup3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/proj_setup3.png
--------------------------------------------------------------------------------
/images/proj_setup_RS.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/proj_setup_RS.png
--------------------------------------------------------------------------------
/images/r_lecture_thumb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/r_lecture_thumb.png
--------------------------------------------------------------------------------
/images/revert1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert1.png
--------------------------------------------------------------------------------
/images/revert10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert10.png
--------------------------------------------------------------------------------
/images/revert2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert2.png
--------------------------------------------------------------------------------
/images/revert3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert3.png
--------------------------------------------------------------------------------
/images/revert4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert4.png
--------------------------------------------------------------------------------
/images/revert5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert5.png
--------------------------------------------------------------------------------
/images/revert6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert6.png
--------------------------------------------------------------------------------
/images/revert7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert7.png
--------------------------------------------------------------------------------
/images/revert8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert8.png
--------------------------------------------------------------------------------
/images/revert9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/revert9.png
--------------------------------------------------------------------------------
/images/rm_components.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/rm_components.png
--------------------------------------------------------------------------------
/images/rmarkdown.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/rmarkdown.png
--------------------------------------------------------------------------------
/images/rstudio_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/rstudio_2.png
--------------------------------------------------------------------------------
/images/rstudio_git_cols.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/rstudio_git_cols.pdf
--------------------------------------------------------------------------------
/images/rstudio_git_cols.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/rstudio_git_cols.png
--------------------------------------------------------------------------------
/images/squid_anatomy.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/squid_anatomy.jpg
--------------------------------------------------------------------------------
/images/stats_r_thumb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/stats_r_thumb.png
--------------------------------------------------------------------------------
/images/styler.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/styler.png
--------------------------------------------------------------------------------
/images/teach.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/teach.png
--------------------------------------------------------------------------------
/images/thomas.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/thomas.png
--------------------------------------------------------------------------------
/images/thomas2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/thomas2.png
--------------------------------------------------------------------------------
/images/tip1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/tip1.png
--------------------------------------------------------------------------------
/images/uoa_map.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/uoa_map.pdf
--------------------------------------------------------------------------------
/images/uoa_map.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/uoa_map.png
--------------------------------------------------------------------------------
/images/which_git.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/which_git.png
--------------------------------------------------------------------------------
/images/workflow1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/workflow1.png
--------------------------------------------------------------------------------
/images/workflow2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/workflow2.png
--------------------------------------------------------------------------------
/images/workflow_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/workflow_3.png
--------------------------------------------------------------------------------
/images/xkcd_files.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/images/xkcd_files.png
--------------------------------------------------------------------------------
/index.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "An Introduction to R"
3 | output:
4 | html_document:
5 | toc: no
6 | ---
7 |
8 | \
9 |
10 | ### Course Introduction
11 |
12 | \
13 |
14 | Welcome to our *Introduction to R* training course. During this course we hope to introduce you to using R, an interactive environment for statistical computing. R in itself is not difficult to learn, but just like any new language the initial learning curve can be a little steep and you will need to use it frequently otherwise it’s easy to forget.
15 |
16 | A few notes about this course. We have tried to simplify the content of this course as much as possible and have based it on 15 years experience teaching (and learning!) R. It is not intended as an introductory statistics course, although we will be using some basic statistics to highlight some of R’s capabilities. Our aim is to help you climb the initial learning curve and provide you with the basic skills to enable you to further your experience in using R. We have included a number of practical [exercises](exercises.html) for you to work through during the course and encourage you complete these in your own time - you certainly won’t learn how to use R by watching other people do it!
17 |
18 | \
19 |
20 | ----
21 |
22 | ### FAQ
23 |
24 | \
25 |
26 | #### How do I use this website?
27 | How you use this website to support your learning and understanding of R is of course up to you. Having said that here are few pointers that have worked for people in the past. The first thing you will need to do is download and install both R and RStudio on your computer. Take a look at the ** Setup** link on the navbar at the top of this page for further instructions on how to set up your computer and download the required datasets. At the heart of this course is our 'Introduction to R book' which you can find by clicking on the ** R Book** link in the navbar. The book is split into 9 Chapters which cover different aspects of using R and RStudio, from general orientation, basic R operations, importing and manipulating data, plotting data, programming in R, R markdown and using version control. You can test your understanding of each of these components by completing the associated exercises which you can find by clicking on ** Exercises**. You will also find the solutions to the exercises here but we suggest that you don't peek at the solutions too quickly and only use them to confirm your answers or if you get stuck and feel like throwing your keyboard out of the window! There are also some additional resources such as lecture slides we use during our in person courses, short how-to videos walking you through some important topics which you can find in the ** Learn R** link. We've also created some stand alone tutorials covering topics such as RStudio Projects, R markdown and version control using Git and GitHub which can be found under the ** Tutorials** link. We suggest that you take a look at the tutorials once you've finished the core part of this course.
28 |
29 | \
30 |
31 | #### What are the pre-requisites for this course?
32 | This course assumes no previous experience or knowledge of using either R or RStudio. It also doesn't assume any knowledge of programming or using a command-line interface, but if you have some experience, the content won’t come as so much of a shock. But don’t panic. Command-line interfaces and programming languages like R are incredibly powerful and will be utterly transformative to your research. There’s a learning curve, and it’s pretty steep in the beginning, but it’s surmountable and the payoff is worth it!
33 |
34 | \
35 |
36 | #### Why are you not teaching us 'tidyverse'?
37 | We have thought long and hard about whether to teach this course only using the ['tidyverse'](https://www.tidyverse.org/){target='_blank'} collection of packages and approaches (if you've never heard of 'tidyverse' before then don't worry about it!). Although we do cover the tidyverse package 'ggplot2', we decided that it was more important that by the end of the course you have a good fundamental grasp of base R which will provide you with the foundation to go on and learn 'tidyverse' approaches in your own time (if you want to). Having said that, if you have previous experience using 'tidyverse' then feel free to complete the course exercises using this approach.
38 |
39 | \
40 |
41 | #### I don't like/want to use RStudio
42 | Not a problem. Feel free to use the IDE or script editor of your choice. One of the great things about R is that *YOU* decide how you want to use it. See [Chapter 1](https://alexd106.github.io/Rbook/alternatives-to-rstudio.html) of our 'Introduction to R' book for some suggested alternatives.
43 |
44 | \
45 |
46 | #### What do I do once I finish the course?
47 | The only way to get more comfortable using R is to use R! We strongly suggest that having completed this course you start using R to summarise, manipulate, plot and analyse your own data as soon as possible. If you don't have any data yet, then ask your friends/supervisor/family for some (I'm sure they will be delighted!) or follow one of the many excellent tutorials available online (see the [resources](resources.html) page for more information). Our suggestion to you, is that whilst you are getting to grips with R, uninstall any other statistics software you have on your computer and only use R. This may seem a little extreme but will hopefully remove the temptation to ‘just do it quickly’ in a more familiar environment and consequently slow down your learning of R. Believe us, anything you can do in your existing statistics software package you can do in R (often better and more efficiently).
48 |
49 | \
50 |
51 | #### Can I give you feedback on this course?
52 | Yes please do! We welcome any and all constructive feedback to help improve this resource. You can find a short (3 minute) feedback form to complete by following this [link](https://forms.gle/U7MbyhRWyLomjyFY7). All feed back is anonymous and only used to help us improve our course material. Many thanks.
53 |
--------------------------------------------------------------------------------
/install_rmarkdown.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Installing R Markdown'
3 | output:
4 | html_document:
5 | toc: yes
6 | toc_depth: 3
7 | ---
8 |
9 |
10 | ```{r setup, include=FALSE}
11 | knitr::opts_chunk$set(echo = TRUE, tidy.opts=list(width.cutoff=55),tidy=TRUE)
12 | ```
13 |
14 | \
15 |
16 | ###Installing R Markdown on a compter running MS Windows
17 |
18 | This guide assumes you have already installed [R](https://www.r-project.org) and the [RStudio IDE](https://www.rstudio.com). RStudio is not required but recommended, because it makes it easier to work with R Markdown. If you do not have RStudio IDE installed, you will also have to install [Pandoc](http://pandoc.org). If you have RStudio installed there is no need to install Pandoc separately because its bundled with RStudio. Next you can install the rmarkdown package in RStudio using the following code:
19 |
20 | ```{r, eval = FALSE}
21 | # Install from CRAN
22 | install.packages('rmarkdown', dep = TRUE)
23 | ```
24 |
25 | You will also need to install a bunch of additional R packages on which rmarkdown depends.
26 |
27 | If you want to generate PDF output, you will need to install LaTeX. For R Markdown users who have not installed LaTeX before, we recommend that you install [TinyTeX](https://yihui.name/tinytex/). You can install TinyTex from within RStudio using the following code:
28 |
29 | ```{r, eval = FALSE}
30 | install.packages('tinytex')
31 | tinytex::install_tinytex() # install TinyTeX
32 | ```
33 |
34 | TinyTeX is a lightweight, portable, cross-platform, and easy-to-maintain LaTeX distribution. The R companion package tinytex can help you automatically install missing LaTeX packages when compiling LaTeX or R Markdown documents to PDF. An alternative option would be to install MiKTeX instead. You can download the latest distribution of [MiKTeX](https://miktex.org/download). Installing MiKTeX is pretty straight forward, but it can sometimes be a pain to get it to play nicely with RStudio. If at all possible we recommend that you use TinyTex.
35 |
36 | With the rmarkdown package, RStudio/Pandoc, and LaTeX, you should be able to compile most R Markdown documents.
37 |
38 | \
39 |
40 | ###Installing R Markdown on a compter running Mac OSX
41 |
42 | This guide assumes you have already installed [R](https://www.r-project.org) and the [RStudio IDE](https://www.rstudio.com). RStudio is not required but recommended, because it makes it easier to work with R Markdown. If you do not have RStudio IDE installed, you will also have to install [Pandoc](http://pandoc.org). If you have RStudio installed there is no need to install Pandoc separately because its bundled with RStudio. Next you can install the rmarkdown package in RStudio using the following code:
43 |
44 | ```{r, eval = FALSE}
45 | # Install from CRAN
46 | install.packages('rmarkdown', dep = TRUE)
47 | ```
48 | You will also need to install a bunch of additional R packages on which rmarkdown depends.
49 |
50 | If you want to generate PDF output, you will need to install LaTeX. For R Markdown users who have not installed LaTeX before, we recommend that you install [TinyTeX](https://yihui.name/tinytex/). You can install TinyTex from within RStudio using the following code:
51 |
52 | ```{r, eval = FALSE}
53 | install.packages('tinytex')
54 | tinytex::install_tinytex() # install TinyTeX
55 | ```
56 |
57 | TinyTeX is a lightweight, portable, cross-platform, and easy-to-maintain LaTeX distribution. The R companion package tinytex can help you automatically install missing LaTeX packages when compiling LaTeX or R Markdown documents to PDF.
58 |
59 | If for some reason TinyTeX does not work on your Mac computer then you can try to install MacTeX instead. You can download the latest version of [MacTeX](http://www.tug.org/mactex/mactex-download.html). Click on the *MacTeX.pkg* link to download. Please be aware that the file is quite large, approximately 3 GB, so it may take some time (also make sure you have enough available space on your computer hard disk). When your download is complete, run the downloaded installer. The installation procedure is quite straightforward. You are given a few options, for example you can choose not to install some components. I recommend you stick with the default settings, so having accepted the license agreement, you can basically just keep clicking 'Continue' on each screen. On the final screen of the wizard, click Install. It may ask for an administrator password. Enter the password, click 'Install Software' and go make a cup of coffee while the installation completes. When the program is done installing, click 'Close' to complete the installation.
60 |
61 | With the rmarkdown package, RStudio/Pandoc, and LaTeX, you should be able to compile most R Markdown documents.
62 |
63 | \
64 |
65 | ###Installing R Markdown on a University teaching computer
66 |
67 | The University computers already have R and RStudio installed with the required R packages (rmarkdown, knitr etc). However, if you want to generate PDF output, you will need to install LaTeX. For R Markdown users who have not installed LaTeX before, we recommend that you install [TinyTeX](https://yihui.name/tinytex/). You can install TinyTex from within R:
68 |
69 | ```{r, eval = FALSE}
70 | install.packages('tinytex')
71 | tinytex::install_tinytex() # install TinyTeX
72 | ```
73 |
74 | TinyTeX is a lightweight, portable, cross-platform, and easy-to-maintain LaTeX distribution. The R companion package tinytex can help you automatically install missing LaTeX packages when compiling LaTeX or R Markdown documents to PDF.
75 |
76 | With the rmarkdown package, RStudio/Pandoc, and LaTeX, you should be able to compile most R Markdown documents.
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/intro2R.Rproj:
--------------------------------------------------------------------------------
1 | Version: 1.0
2 |
3 | RestoreWorkspace: Default
4 | SaveWorkspace: Default
5 | AlwaysSaveHistory: Default
6 |
7 | EnableCodeIndexing: Yes
8 | UseSpacesForTab: Yes
9 | NumSpacesForTab: 2
10 | Encoding: UTF-8
11 |
12 | RnwWeave: Sweave
13 | LaTeX: XeLaTeX
14 |
15 | BuildType: Website
16 |
--------------------------------------------------------------------------------
/lectures.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Lectures"
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | \
9 |
10 | Lecture slides that we deliver during our in-person courses to help support you whilst learning R. This material should be used in conjunction with the [Introduction to R](https://alexd106.github.io/Rbook) book.
11 |
12 | Either tap on the slides or use your keyboard arrow keys (← →) to scroll through the slides. Press 'h' for other slide options.
13 |
14 | \
15 |
16 | ```{r, reveal, echo=FALSE, eval = isFALSE(show_lecture)}
17 | cat("Lectures will be released as the course progresses")
18 | ```
19 |
20 | \
21 |
22 | ```{r intro-lec, echo=FALSE}
23 | knitr::include_url('https://alexd106.github.io/Rintro_lec/Rintro_lecture#1')
24 | ```
25 |
26 | \
27 |
28 | ```{r data-lec, echo=FALSE}
29 | knitr::include_url('https://alexd106.github.io/Rdata_lec/Rdata_lecture#1')
30 | ```
31 |
32 | \
33 |
34 | ```{r stat-lec, echo=FALSE}
35 | knitr::include_url('https://alexd106.github.io/Rstats_lec/Rstats_lecture#1')
36 | ```
37 |
38 | \
39 |
40 |
41 |
--------------------------------------------------------------------------------
/lectures/getting_the_data_in_r.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/lectures/getting_the_data_in_r.pdf
--------------------------------------------------------------------------------
/lectures/introduction_to_r_2020.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/lectures/introduction_to_r_2020.pdf
--------------------------------------------------------------------------------
/lectures/statistics_in_r.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/lectures/statistics_in_r.pdf
--------------------------------------------------------------------------------
/people_details:
--------------------------------------------------------------------------------
1 | #### Deon Roos
2 |
7 |
8 | \
9 |
10 | Deon is a PhD student in applied ecology at the University of Aberdeen researching spatial variation of the temporal kind in population dynamics. He has been using and teaching R for 5 years.
11 |
12 | - Email: deon(dot)roos(at)abdn(dot)ac(dot)uk
13 | - Web: https://www.abdn.ac.uk/people/deon.roos
14 | - Twitter: https://twitter.com/DeonRoos88
15 | - GitHub: https://github.com/Deon88
16 |
17 | \
18 |
19 | \
20 |
21 | #### Ana Couto
22 |
');
74 | $(tabs[0]).before(tabList);
75 | var tabContent = $('');
76 | $(tabs[0]).before(tabContent);
77 |
78 | // build the tabset
79 | var activeTab = 0;
80 | tabs.each(function(i) {
81 |
82 | // get the tab div
83 | var tab = $(tabs[i]);
84 |
85 | // get the id then sanitize it for use with bootstrap tabs
86 | var id = tab.attr('id');
87 |
88 | // see if this is marked as the active tab
89 | if (tab.hasClass('active'))
90 | activeTab = i;
91 |
92 | // remove any table of contents entries associated with
93 | // this ID (since we'll be removing the heading element)
94 | $("div#" + tocID + " li a[href='#" + id + "']").parent().remove();
95 |
96 | // sanitize the id for use with bootstrap tabs
97 | id = id.replace(/[.\/?&!#<>]/g, '').replace(/\s/g, '_');
98 | tab.attr('id', id);
99 |
100 | // get the heading element within it, grab it's text, then remove it
101 | var heading = tab.find('h' + tabLevel + ':first');
102 | var headingText = heading.html();
103 | heading.remove();
104 |
105 | // build and append the tab list item
106 | var a = $('' + headingText + '');
107 | a.attr('href', '#' + id);
108 | a.attr('aria-controls', id);
109 | var li = $('');
110 | li.append(a);
111 | tabList.append(li);
112 |
113 | // set it's attributes
114 | tab.attr('role', 'tabpanel');
115 | tab.addClass('tab-pane');
116 | tab.addClass('tabbed-pane');
117 | if (fade)
118 | tab.addClass('fade');
119 |
120 | // move it into the tab content div
121 | tab.detach().appendTo(tabContent);
122 | });
123 |
124 | // set active tab
125 | $(tabList.children('li')[activeTab]).addClass('active');
126 | var active = $(tabContent.children('div.section')[activeTab]);
127 | active.addClass('active');
128 | if (fade)
129 | active.addClass('in');
130 |
131 | if (tabset.hasClass("tabset-sticky"))
132 | tabset.rmarkdownStickyTabs();
133 | }
134 |
135 | // convert section divs with the .tabset class to tabsets
136 | var tabsets = $("div.section.tabset");
137 | tabsets.each(function(i) {
138 | buildTabset($(tabsets[i]));
139 | });
140 | };
141 |
142 |
--------------------------------------------------------------------------------
/site_libs/tocify-1.9.1/jquery.tocify.css:
--------------------------------------------------------------------------------
1 | /*
2 | * jquery.tocify.css 1.9.1
3 | * Author: @gregfranko
4 | */
5 |
6 | /* The Table of Contents container element */
7 | .tocify {
8 | width: 20%;
9 | max-height: 90%;
10 | overflow: auto;
11 | margin-left: 2%;
12 | position: fixed;
13 | border: 1px solid #ccc;
14 | border-radius: 6px;
15 | }
16 |
17 | /* The Table of Contents is composed of multiple nested unordered lists. These styles remove the default styling of an unordered list because it is ugly. */
18 | .tocify ul, .tocify li {
19 | list-style: none;
20 | margin: 0;
21 | padding: 0;
22 | border: none;
23 | line-height: 30px;
24 | }
25 |
26 | /* Top level header elements */
27 | .tocify-header {
28 | text-indent: 10px;
29 | }
30 |
31 | /* Top level subheader elements. These are the first nested items underneath a header element. */
32 | .tocify-subheader {
33 | text-indent: 20px;
34 | display: none;
35 | }
36 |
37 | /* Makes the font smaller for all subheader elements. */
38 | .tocify-subheader li {
39 | font-size: 12px;
40 | }
41 |
42 | /* Further indents second level subheader elements. */
43 | .tocify-subheader .tocify-subheader {
44 | text-indent: 30px;
45 | }
46 | .tocify-subheader .tocify-subheader .tocify-subheader {
47 | text-indent: 40px;
48 | }
49 | .tocify-subheader .tocify-subheader .tocify-subheader .tocify-subheader {
50 | text-indent: 50px;
51 | }
52 | .tocify-subheader .tocify-subheader .tocify-subheader .tocify-subheader .tocify-subheader {
53 | text-indent: 60px;
54 | }
55 |
56 | /* Twitter Bootstrap Override Style */
57 | .tocify .tocify-item > a, .tocify .nav-list .nav-header {
58 | margin: 0px;
59 | }
60 |
61 | /* Twitter Bootstrap Override Styles */
62 | .tocify .tocify-item a, .tocify .list-group-item {
63 | padding: 5px;
64 | }
65 |
66 | .tocify .nav-pills > li {
67 | float: none;
68 | }
69 |
70 | /* We don't override the bootstrap colors because this gives us the
71 | wrong selection colors when using bootstrap themes
72 |
73 | .tocify .list-group-item:hover, .tocify .list-group-item:focus {
74 | background-color: #f5f5f5;
75 | }
76 |
77 | .tocify .list-group-item.active:hover, .tocify .list-group-item.active:focus {
78 | background-color: #428bca;
79 | }
80 | */
81 |
82 | /* End Twitter Bootstrap Override Styles */
83 |
--------------------------------------------------------------------------------
/squid_analysis.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: "Squid Analysis"
3 | author: "Alex Douglas"
4 | date: "27/02/2020"
5 | output:
6 | html_document:
7 | toc: no
8 | pdf_document: default
9 |
10 | ---
11 |
12 | ```{r global_options, include=FALSE}
13 |
14 | knitr::opts_chunk$set(message=FALSE, tidy.opts=list(width.cutoff=60),tidy=TRUE)
15 |
16 | ```
17 |
18 |
19 | \
20 |
21 | ### Sampling and data description
22 |
23 | These data were originally collected as part of a study published in Aquatic Living Resources (Smith *et al*., 2005). The aim of the study was to investigate the seasonal patterns of investment in somatic and reproductive tissues in the long finned squid *Loligo forbesi* caught in Scottish waters. Squid were caught monthly from December 1989 - July 1991 (**month** and **year variables**). After capture, each squid was given a unique specimen code (**specimen variable**) and the following variables measured:
24 |
25 | \
26 |
27 | - **weight variable** - body weight (g)
28 | - **sex variable** - sex (only female squid are included here)
29 | - **DML variable** - individual dorsal mantle length (mm)
30 | - **eviscerate.weight variable** - mantle weight measured without internal organs (g)
31 | - **ovary.weight variable** - gonad weight (g)
32 | - **nid.weight variable** - nidamental gland weight (g)
33 | - **nid.length variable** - nidamental gland length (g)
34 | - **dig.weight variable** - digestive gland weight (g)
35 |
36 | \
37 |
38 | Each individual was also assigned a categorical measure of maturity (**maturity.stage variable**) ranging from 1 to 5 with 1 = immature, 5 = mature.
39 |
40 | Some interesting background information on squid morphology can be found [here](https://en.wikipedia.org/wiki/Loligo_forbesii) and the following image provides a useful summary of squid anatomy.
41 |
42 | \pagebreak
43 |
44 | {width=70%}
45 |
46 | \
47 |
48 | ### Data import and exploration
49 |
50 | \
51 |
52 | ```{r, data-import}
53 | squid <- read.table('./data/squid1.txt', header = TRUE)
54 | str(squid, vec.len = 2)
55 | ```
56 |
57 | In this dataset `r nrow(squid)` squid were caught and `r ncol(squid)` variables were measured for each squid. Details are shown above.
58 |
59 | ```{r, data-recode, echo=FALSE}
60 | # convert variables to factors
61 | squid$Fmaturity <- factor(squid$maturity.stage)
62 | squid$Fmonth <- factor(squid$month)
63 | squid$Fyear <- factor(squid$year)
64 | ```
65 |
66 | \
67 |
68 | The variables `maturity.stage`, `month` and `year` were converted from integers to factors in the dataframe `squid`. These recoded variables were named `Fmaturity`, `Fmonth` and `Fyear`.
69 |
70 | \
71 |
72 | Next, let's take a look at the number of observations across years and months.
73 |
74 | \
75 |
76 | ```{r, data-obs}
77 | library(knitr)
78 | kable(table(squid$Fmonth, squid$Fyear), row.names = TRUE, format = 'markdown')
79 | ```
80 |
81 | \
82 |
83 | In 1989 data were only collected during December and in 1991 data collection stopped in August. During 1990, no data were collected in either February or June. There are also some months that have very few observations (May 1990 and July 1991 for example) so care must be taken when modelling these data.
84 |
85 | \
86 |
87 |
88 |
89 | ```{r, data-obs2, include=FALSE}
90 | library(pander)
91 | mytab <- table(squid$Fmonth, squid$Fyear)
92 | names(dimnames(mytab)) <- c("Month", "Year")
93 | pander(ftable(mytab))
94 | ```
95 |
96 | \
97 |
98 | Number of observations in each month for each of the squid maturity stages are given in the table below.
99 |
100 | \
101 |
102 | ```{r, maturity-obs, echo=FALSE}
103 | library(kableExtra)
104 |
105 | kable(table(squid$Fmaturity, squid$Fmonth), row.names = TRUE, format = 'markdown')
106 | ```
107 |
108 | \
109 |
110 | Not all maturity stages were observed in all months. Very few squid of maturity stage 1, 2 or 3 were caught in the months January to May whereas maturity stages 4 and 5 were predominantly caught during these months.
111 |
112 | \
113 |
114 | Now let's check for any unusual observations in the variables; `DML`, `weight`, `nid.length` and `ovary.weight`.
115 |
116 | \
117 |
118 | ```{r, dotplot}
119 | par(mfrow = c(2, 2))
120 | dotchart(squid$DML, main = "DML")
121 | dotchart(squid$weight, main = "weight")
122 | dotchart(squid$nid.length, main = "nid length")
123 | dotchart(squid$ovary.weight, main = "ovary weight")
124 | ```
125 |
126 | \
127 |
128 | It looks like the variable `nid.length` contains an **unusually large** value. Actually, this value is biologically implausible and clearly an error. I went back and checked my field notebook and sure enough it's a typo. I was knackered at the time and accidentally inserted a zero by mistake when transcribing these data. **Doh!** This squid was identified as `r which(squid$nid.length > 400)` with a sample number `r squid$sample.no[which(squid$nid.length > 400)]`. This observation was subsequently removed from the data set.
129 |
130 | \
131 |
132 | Let's take a look at whether DML changes with maturity stage.
133 |
134 | \
135 |
136 | ```{r, maturity-dml, echo=FALSE, fig.width=5, fig.height=4, fig.align='center'}
137 |
138 | boxplot(DML ~ Fmaturity, data = squid, xlab = "maturity stage", ylab = "DML")
139 |
140 | ```
141 |
142 | DML was lowest for maturity stage 1 with a mean length of `r round(mean(squid$DM[squid$Fmaturity == 1]), digits = 2)` mm. DML increased until maturity stage 3 (mean `r round(mean(squid$DM[squid$Fmaturity == 3]), digits = 2)` mm) after which it remained reasonably consistent for maturity stages 4 (mean `r round(mean(squid$DM[squid$Fmaturity == 4]), digits = 2)` mm) and 5 (mean `r round(mean(squid$DM[squid$Fmaturity == 5]), digits = 2)` mm).
143 |
144 | \
145 |
146 | ### Session Information
147 |
148 |
149 | ```{r, session-info, eval=FALSE}
150 | sessionInfo()
151 | ```
152 |
153 |
154 |
155 |
156 | ```{r, session-info2, echo = FALSE}
157 | pander::pander(sessionInfo())
158 | ```
159 |
--------------------------------------------------------------------------------
/squid_analysis.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/squid_analysis.pdf
--------------------------------------------------------------------------------
/squid_analysis_files/figure-html/dotplot-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/squid_analysis_files/figure-html/dotplot-1.png
--------------------------------------------------------------------------------
/squid_analysis_files/figure-html/maturity-dml-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexd106/intro2R/861b33c5655736d8ce83bb6c267490da94821639/squid_analysis_files/figure-html/maturity-dml-1.png
--------------------------------------------------------------------------------
/syllabus.Rmd:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'Virtual syllabus'
3 | output:
4 | html_document:
5 | toc: false
6 | ---
7 |
8 | \
9 |
10 | We estimate that this course will take approximately three days to cover the core material contained in Chapters 1 - 4 and Chapter 6 of our [Introduction to R book](https://intro2r.com/), but this will naturally vary between individuals. Of course, how you choose to cover the material in these Chapters is up to you. If you plan on ring fencing a block of time to complete the whole course then we suggest the timetable below. However, this may not be an option (or optimal) for everyone, in which case we suggest that you try to complete the material for each Chapter in a single session (perhaps in either a morning or an afternoon).
11 |
12 | \
13 |
14 | #### Day 1
15 |
16 | - Morning: Getting to know R and RStudio ([Chapter 1](https://intro2r.com/chap1.html))
17 |
18 | - Afternoon: Basic R operations ([Chapter 2](https://intro2r.com/basics-r.html))
19 |
20 | \
21 |
22 | #### Day 2
23 |
24 | - Morning: Importing and manipulating dataframes ([Chapter 3](https://intro2r.com/data-r.html))
25 |
26 | - Afternoon: Plotting data in R using base and lattice graphics ([Chapter 4](https://intro2r.com/graphics-base-r.html))
27 |
28 | \
29 |
30 | #### Day 3
31 |
32 | - Morning: Simple statistics in R ([Chapter 6](https://intro2r.com/stats-r.html))
33 |
34 | - Afternoon: Optional - Basic programming in R ([Chapter 7](https://intro2r.com/prog-r.html))
--------------------------------------------------------------------------------
/utils.R:
--------------------------------------------------------------------------------
1 |
2 | # generate thumbnail from image
3 | thumbnail <- function(title, img, href, caption = TRUE) {
4 | div(class = "col-sm-4",
5 | a(class = "thumbnail", title = title, href = href,
6 | img(src = img),
7 | div(class = if (caption) "caption",
8 | if (caption) title)
9 | )
10 | )
11 | }
--------------------------------------------------------------------------------
/video_links:
--------------------------------------------------------------------------------
1 | Installing R and RStudio
2 |
3 |
4 |
5 | Introducing RStudio
6 |
7 |
--------------------------------------------------------------------------------