-
Notifications
You must be signed in to change notification settings - Fork 0
/
solutions.Rmd
275 lines (212 loc) · 5.81 KB
/
solutions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
---
title: "Exercises"
output:
html_document:
toc: true
toc_depth: 4
---
**[Back to main page](index.html)**
## Lesson 01: Analyzing Patient Data
### Slicing (Subsetting) Data
A subsection of a data frame is called a slice.
We can take slices of character vectors as well:
```{r}
animal <- c("m", "o", "n", "k", "e", "y")
# first three characters
animal[1:3]
# last three characters
animal[4:6]
```
1. If the first four characters are selected using the slice `animal[1:4]`, how can we obtain the first four characters in reverse order?
2. What is `animal[-1]`?
What is `animal[-4]`?
Given those answers,
explain what `animal[-1:-4]` does.
3. Use a slice of `animal` to create a new character vector that spells the word "eon", i.e. `c("e", "o", "n")`.
#### Solution
1.
```{r}
animal[4:1]
```
2.
```{r}
animal[-1]
```
```{r}
animal[-4]
```
```{r}
animal[-1:-4]
```
-1:-4 creates a slice from -1 to -4: -1, -2, -3, -4.
Those numbers are then indexed after animal: animal[c(-1, -2, -3, -4)], which results in the first four entries of animal being removed.
### Plotting Data
Create a plot showing the standard deviation of the inflammation data for each day across all patients.
#### Solution
```{r, eval=FALSE}
sd_day_inflammation <- apply(dat, 2, sd)
plot(sd_day_inflammation)
```
---
## Lesson 02: Creating Functions
### Functions to Create Graphs
Write a function called `analyze` that takes a filename as a argument
and displays the three graphs produced in the previous lesson (average, min and max inflammation over time).
`analyze("data/inflammation-01.csv")` should produce the graphs already shown,
while `analyze("data/inflammation-02.csv")` should produce corresponding graphs for the second data set.
Be sure to document your function with comments.
#### Solution
```{r}
analyze <- function(filename) {
# Plots the average, min, and max inflammation over time.
# Input is character string of a csv file.
dat <- read.csv(file = filename, header = FALSE)
avg_day_inflammation <- apply(dat, 2, mean)
plot(avg_day_inflammation)
max_day_inflammation <- apply(dat, 2, max)
plot(max_day_inflammation)
min_day_inflammation <- apply(dat, 2, min)
plot(min_day_inflammation)
}
```
---
## Lesson 03: Analyzing Multiple Data Sets
### Printing Numbers
R has a built-in function called `seq` that creates a list of numbers:
```{r}
seq(3)
```
Using `seq`, write a function that prints the first **N** natural numbers, one per line:
```{r, echo=-1}
print_N <- function(N) {
nseq <- seq(N)
for (num in nseq) {
print(num)
}
}
print_N(3)
```
#### Solution
```{r}
print_N <- function(N) {
nseq <- seq(N)
for (num in nseq) {
print(num)
}
}
```
### Summing Values
Write a function called `total` that calculates the sum of the values in a vector.
(R has a built-in function called `sum` that does this for you.
Please don't use it for this exercise.)
```{r, echo=-1}
total <- function(vec) {
#calculates the sum of the values in a vector
vec_sum <- 0
for (num in vec) {
vec_sum <- vec_sum + num
}
return(vec_sum)
}
ex_vec <- c(4, 8, 15, 16, 23, 42)
total(ex_vec)
```
#### Solution
```{r}
total <- function(vec) {
# calculates the sum of the values in a vector
vec_sum <- 0
for (num in vec) {
vec_sum <- vec_sum + num
}
return(vec_sum)
}
```
### Exponentiation
Exponentiation is built into R:
```{r}
2^4
```
Write a function called `expo` that uses a loop to calculate the same result.
```{r, echo=-1}
expo <- function(base, power) {
result <- 1
for (i in seq(power)) {
result <- result * base
}
return(result)
}
expo(2, 4)
```
#### Solution
```{r}
expo <- function(base, power) {
result <- 1
for (i in seq(power)) {
result <- result * base
}
return(result)
}
```
### Using Loops to Analyze Multiple Files
Write a function called `analyze_all` that takes a filename pattern as its sole argument and runs `analyze` for each file whose name matches the pattern.
#### Solution
```{r}
analyze_all <- function(pattern) {
# Runs the function analyze for each file in the "data" directory
# that contains the given pattern.
filenames <- list.files(path = "data", pattern = pattern, full.names = TRUE)
for (f in filenames) {
analyze(f)
}
}
```
---
## Lesson 04: Making Choices
### Choosing Plots Based on Data
Write a function `plot_dist` that plots
a boxplot if the length of the vector is greater than a specified threshold
and a stripchart otherwise.
To do this you'll use the R functions `boxplot` and `stripchart`.
```{r using-conditions-01, eval=FALSE}
dat <- read.csv("data/inflammation-01.csv", header = FALSE)
plot_dist(dat[, 10], threshold = 10) # day (column) 10
plot_dist(dat[1:5, 10], threshold = 10) # samples (rows) 1-5 on day (column) 10
```
#### Solution
```{r}
plot_dist <- function(x, threshold) {
if (length(x) > threshold) {
boxplot(x)
} else {
stripchart(x)
}
}
```
### Changing the Behavior of the Plot Command
One of your collaborators asks if you can recreate the figures with lines instead of points.
Find the relevant argument to `plot` by reading the documentation (`?plot`),
update `analyze`, and then recreate all the figures with `analyze_all`.
#### Solution
```{r}
analyze <- function(filename, output = NULL) {
# Plots the average, min, and max inflammation over time.
# Input:
# filename: character string of a csv file
# output: character string of pdf file for saving
if (!is.null(output)) {
pdf(output)
}
dat <- read.csv(file = filename, header = FALSE)
avg_day_inflammation <- apply(dat, 2, mean)
plot(avg_day_inflammation, type = "l")
max_day_inflammation <- apply(dat, 2, max)
plot(max_day_inflammation, type = "l")
min_day_inflammation <- apply(dat, 2, min)
plot(min_day_inflammation, type = "l")
if (!is.null(output)) {
dev.off()
}
}
```
**[Back to main page](index.html)**