forked from swcarpentry/r-novice-inflammation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-starting-with-data.Rmd
386 lines (295 loc) · 14.7 KB
/
01-starting-with-data.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
---
layout: page
title: Programming with R
subtitle: Analyzing patient data
minutes: 30
---
```{r, include = FALSE}
source("tools/chunk-options.R")
opts_chunk$set(fig.path = "fig/01-starting-with-data-")
```
> ## Learning Objectives {.objectives}
> * Read tabular data from a file into a program.
> * Assign values to variables.
> * Select individual values and subsections from data.
> * Perform operations on a data frame of data.
> * Display simple graphs.
We are studying inflammation in patients who have been given a new treatment for arthritis,
and need to analyze the first dozen data sets.
The data sets are stored in [comma-separated values](reference.html#comma-separated-values-(csv)) (CSV) format. Each row holds the observations for just one patient. Each column holds the inflammation measured in a day, so we have a set of values in successive days.
The first few rows of our first file look like this:
```{r echo = FALSE}
tmp <- read.csv("data/inflammation-01.csv", header = FALSE, nrows = 5)
write.table(tmp, quote = FALSE, sep = ",", row.names = FALSE, col.names = FALSE)
rm(tmp)
```
We want to:
* Load data into memory,
* Calculate the average value of inflammation per day across all patients, and
* Plot the results.
To do all that, we'll have to learn a little bit about programming.
### Loading Data
To load our inflammation data, first we need to tell our computer where is the file that contains the values. We have been told its name is `inflammation-01.csv`. This is very important in R, if we forget this step we’ll get an error message when trying to read the file. We can change the current working directory using the function `setwd`. For this example, we change the path to the directory we just created:
```{r,eval=FALSE}
setwd("~/Desktop/r-novice-inflammation/)
```
Just like in the Unix Shell, we type the command and then press `Enter` (or `return`).
Alternatively you can change the working directory using the RStudio GUI using the menu option `Session` -> `Set Working Directory` -> `Choose Directory...`
The data files are located in the directory `data` inside the working directory. Now we can load the data into R using `read.csv`:
```{r, results="hide"}
read.csv(file = "data/inflammation-01.csv", header = FALSE)
```
The expression `read.csv(...)` is a [function call](reference.html#function-call) that asks R to run the function `read.csv`.
`read.csv` has two [arguments](reference.html#argument): the name of the file we want to read, and whether the first line of the file contains names for the columns of data.
The filename needs to be a character string (or [string](reference.html#string) for short), so we put it in quotes. Assigning the second argument, `header`, to be `FALSE` indicates that the data file does not have column headers. We'll talk more about the value `FALSE`, and its converse `TRUE`, in lesson 04.
> ## Tip {.callout}
>
> `read.csv` actually has many more arguments that you may find useful when
> importing your own data in the future. You can learn more about these
> options in this supplementary [lesson](01-supp-read-write-csv.html).
The utility of a function is that it will perform its given action on whatever value is passed to the named argument(s).
For example, in this case if we provided the name of a different file to the argument `file`, `read.csv` would read it instead.
We'll learn more of the details about functions and their arguments in the next lesson.
Since we didn't tell it to do anything else with the function's output, the console will display the full contents of the file `inflammation-01.csv`.
Try it out.
`read.csv` read the file, but we can't use data unless we assign it to a variable.
A variable is just a name for a value, such as `x`, `current_temperature`, or `subject_id`.
We can create a new variable simply by assigning a value to it using `<-`
```{r}
weight_kg <- 55
```
Once a variable has a value, we can print it by typing the name of the variable and hitting `Enter` (or `return`).
In general, R will print to the console any object returned by a function or operation *unless* we assign it to a variable.
```{r}
weight_kg
```
We can do arithmetic with the variable:
```{r}
# weight in pounds:
2.2 * weight_kg
```
> ## Tip {.callout}
>
> We can add comments to our code using the `#` character. It is useful to
> document our code in this way so that others (and us the next time we
> read it) have an easier time following what the code is doing.
We can also change an object's value by assigning it a new value:
```{r}
weight_kg <- 57.5
# weight in kilograms is now
weight_kg
```
If we imagine the variable as a sticky note with a name written on it,
assignment is like putting the sticky note on a particular value:
<img src="fig/python-sticky-note-variables-01.svg" alt="Variables as Sticky Notes" />
This means that assigning a value to one object does not change the values of other variables.
For example, let's store the subject's weight in pounds in a variable:
```{r}
weight_lb <- 2.2 * weight_kg
# weight in kg...
weight_kg
# ...and in pounds
weight_lb
```
<img src="fig/python-sticky-note-variables-02.svg" alt="Creating Another Variable" />
and then change `weight_kg`:
```{r}
weight_kg <- 100.0
# weight in kg now...
weight_kg
# ...and weight in pounds still
weight_lb
```
<img src="fig/python-sticky-note-variables-03.svg" alt="Updating a Variable" />
Since `weight_lb` doesn't "remember" where its value came from, it isn't automatically updated when `weight_kg` changes.
This is different from the way spreadsheets work.
> ## Tip {.callout}
>An alternative way to print the value of a variable is to use () around the assignment statement. As an example: `(total_weight <- weight_kg + weight_lb)`, adds the values of `weight_kg` and `weight_lb`, assigns the result to the `total_weight`, and finally prints the assigned value of the variable `total_weight`.
Now that we know how to assign things to variables, let's re-run `read.csv` and save its result:
```{r}
dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE)
```
This statement doesn't produce any output because assignment doesn't display anything.
If we want to check that our data has been loaded, we can print the variable's value.
However, for large data sets it is convenient to use the function `head` to display only the first few rows of data.
```{r}
head(dat)
```
> ## Challenge - Assigning values to variables {.challenge}
>
> Draw diagrams showing what variables refer to what values after each statement in the following program:
>
~~~{.r}
mass <- 47.5
age <- 122
mass <- mass * 2.0
age <- age - 20
~~~
### Manipulating Data
Now that our data is loaded in memory, we can start doing things with it.
First, let's ask what type of thing `dat` is:
```{r}
class(dat)
```
The output tells us that is a data frame. Think of this structure as a spreadsheet in MS Excel that many of us are familiar with.
Data frames are very useful for storing data and you will find them elsewhere when programming in R. A typical data frame of experimental data contains individual observations in rows and variables in columns.
We can see the shape, or [dimensions](reference.html#dimensions-(of-an-array)), of the data frame with the function `dim`:
```{r}
dim(dat)
```
This tells us that our data frame, `dat`, has `r nrow(dat)` rows and `r ncol(dat)` columns.
If we want to get a single value from the data frame, we can provide an [index](reference.html#index) in square brackets, just as we do in math:
```{r}
# first value in dat
dat[1, 1]
# middle value in dat
dat[30, 20]
```
An index like `[30, 20]` selects a single element of a data frame, but we can select whole sections as well.
For example, we can select the first ten days (columns) of values for the first four patients (rows) like this:
```{r}
dat[1:4, 1:10]
```
The [slice](reference.html#slice) `1:4` means, "Start at index 1 and go to index 4."
The slice does not need to start at 1, e.g. the line below selects rows 5 through 10:
```{r}
dat[5:10, 1:10]
```
We can use the function `c`, which stands for **c**ombine, to select non-contiguous values:
```{r}
dat[c(3, 8, 37, 56), c(10, 14, 29)]
```
We also don't have to provide a slice for either the rows or the columns.
If we don't include a slice for the rows, R returns all the rows; if we don't include a slice for the columns, R returns all the columns.
If we don't provide a slice for either rows or columns, e.g. `dat[, ]`, R returns the full data frame.
```{r}
# All columns from row 5
dat[5, ]
# All rows from column 16
dat[, 16]
```
Now let's perform some common mathematical operations to learn about our inflammation data.
When analyzing data we often want to look at partial statistics, such as the maximum value per patient or the average value per day.
One way to do this is to select the data we want to create a new temporary data frame, and then perform the calculation on this subset:
```{r}
# first row, all of the columns
patient_1 <- dat[1, ]
# max inflammation for patient 1
max(patient_1)
```
We don't actually need to store the row in a variable of its own.
Instead, we can combine the selection and the function call:
```{r}
# max inflammation for patient 2
max(dat[2, ])
```
R also has functions for other common calculations, e.g. finding the minimum, mean, median, and standard deviation of the data:
```{r}
# minimum inflammation on day 7
min(dat[, 7])
# mean inflammation on day 7
mean(dat[, 7])
# median inflammation on day 7
median(dat[, 7])
# standard deviation of inflammation on day 7
sd(dat[, 7])
```
What if we need the maximum inflammation for all patients, or the average for each day?
As the diagram below shows, we want to perform the operation across a margin of the data frame:
<img src="fig/r-operations-across-axes.svg" alt="Operations Across Axes" />
To support this, we can use the `apply` function.
> ## Tip {.callout}
>
> To learn about a function in R, e.g. `apply`, we can read its help
> documention by running `help(apply)` or `?apply`.
`apply` allows us to repeat a function on all of the rows (`MARGIN = 1`) or columns (`MARGIN = 2`) of a data frame.
Thus, to obtain the average inflammation of each patient we will need to calculate the mean of all of the rows (`MARGIN = 1`) of the data frame.
```{r}
avg_patient_inflammation <- apply(dat, 1, mean)
```
And to obtain the average inflammation of each day we will need to calculate the mean of all of the columns (`MARGIN = 2`) of the data frame.
```{r}
avg_day_inflammation <- apply(dat, 2, mean)
```
Since the second argument to `apply` is `MARGIN`, the above command is equivalent to `apply(dat, MARGIN = 2, mean)`.
We'll learn why this is so in the next lesson.
> ## Tip {.callout}
>
> Some common operations have more efficient alternatives. For example, you
> can calculate the row-wise or column-wise means with `rowMeans` and
> `colMeans`, respectively.
> ## Challenge - Slicing (subsetting) data {.challenge}
>
> A subsection of a data frame is called a [slice](reference.html#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?
>
> 1. What is `animal[-1]`?
> What is `animal[-4]`?
> Given those answers,
> explain what `animal[-1:-4]` does.
>
> 1. Use a slice of `animal` to create a new character vector that spells the word "eon", i.e. `c("e", "o", "n")`.
> ## Challenge - Subsetting data 2 {.challenge}
>
> Suppose you want to determine the maximum inflamation for patient 5 across days three to seven.
> To do this you would extract the relevant slice from the data frame and calculate the maximum value.
> Which of the following lines of R code gives the correct answer?
>
> (a) `max(dat[5, ])`
> (b) `max(dat[3:7, 5])`
> (c) `max(dat[5, 3:7])`
> (d) `max(dat[5, 3, 7])`
### Plotting
The mathematician Richard Hamming once said, "The purpose of computing is insight, not numbers," and the best way to develop insight is often to visualize data.
Visualization deserves an entire lecture (or course) of its own, but we can explore a few of R's plotting features.
Let's take a look at the average inflammation over time.
Recall that we already calculated these values above using `apply(dat, 2, mean)` and saved them in the variable `avg_day_inflammation`.
Plotting the values is done with the function `plot`.
```{r plot-avg-inflammation}
plot(avg_day_inflammation)
```
Above, we gave the function `plot` a vector of numbers corresponding to the average inflammation per day across all patients.
`plot` created a scatter plot where the y-axis is the average inflammation level and the x-axis is the order, or index, of the values in the vector, which in this case correspond to the 40 days of treatment.
The result is roughly a linear rise and fall, which is suspicious: based on other studies, we expect a sharper rise and slower fall.
Let's have a look at two other statistics: the maximum and minimum inflammation per day.
```{r plot-max-inflammation}
max_day_inflammation <- apply(dat, 2, max)
plot(max_day_inflammation)
```
```{r plot-min-inflammation}
min_day_inflammation <- apply(dat, 2, min)
plot(min_day_inflammation)
```
The maximum value rises and falls perfectly smoothly, while the minimum seems to be a step function. Neither result seems particularly likely, so either there's a mistake in our calculations or something is wrong with our data.
> ## Challenge - Plotting data {.challenge}
>
> Create a plot showing the standard deviation of the inflammation data for each day across all patients.
> ## Key Points {.callout}
>
> * Use `variable <- value` to assign a value to a variable in order to record it in memory.
> * Objects are created on demand whenever a value is assigned to them.
> * The function `dim` gives the dimensions of a data frame.
> * Use `object[x, y]` to select a single element from a data frame.
> * Use `from:to` to specify a sequence that includes the indices from `from` to
>`to`.
> * All the indexing and slicing that works on data frames also works on vectors.
> * Use `#` to add comments to programs.
> * Use `mean`, `max`, `min` and `sd` to calculate simple statistics.
> * Use `apply` to calculate statistics across the rows or columns of a data frame.
> * Use `plot` to create simple visualizations.
> ## Next Steps {.callout}
>
> Our work so far has convinced us that something's wrong with our first data file.
> We would like to check the other 11 the same way, but typing in the same commands repeatedly is tedious and error-prone.
> Since computers don't get bored (that we know of), we should create a way to do a complete analysis with a single command, and then figure out how to repeat that step once for each file.
> These operations are the subjects of the next two lessons.