forked from swcarpentry/r-novice-gapminder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
05-data-structures-part2.html
594 lines (577 loc) · 38.3 KB
/
05-data-structures-part2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: R for reproducible scientific analysis</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
<link rel="stylesheet" type="text/css" href="css/swc.css" />
<link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
<meta charset="UTF-8" />
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="lesson">
<div class="container card">
<div class="banner">
<a href="http://software-carpentry.org" title="Software Carpentry">
<img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
</a>
</div>
<article>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<a href="index.html"><h1 class="title">R for reproducible scientific analysis</h1></a>
<h2 class="subtitle">Data frames and reading in data</h2>
<section class="objectives panel panel-warning">
<div class="panel-heading">
<h2 id="learning-objectives"><span class="glyphicon glyphicon-certificate"></span>Learning Objectives</h2>
</div>
<div class="panel-body">
<ul>
<li>Become familiar with data frames</li>
<li>Be able to read regular data into R</li>
</ul>
</div>
</section>
<h2 id="data-frames">Data frames</h2>
<p>Data frames are similar to matrices, except each column can be a different atomic type. A data frames is the standard structure for storing and manipulating rectangular data sets. Underneath the hood, data frames are really lists, where each element is an atomic vector, with the added restriction that they’re all the same length. As you will see, if we pull out one column of a data frame,we will have a vector. You will probably find that data frames are more complicated than vectors and other data structures we have considered, but they provide powerful capabilities.</p>
<p>Data frames can be created manually with the <code>data.frame</code> function:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">id =</span> <span class="kw">c</span>(<span class="st">'a'</span>, <span class="st">'b'</span>, <span class="st">'c'</span>, <span class="st">'d'</span>, <span class="st">'e'</span>, <span class="st">'f'</span>), <span class="dt">x =</span> <span class="dv">1</span>:<span class="dv">6</span>, <span class="dt">y =</span> <span class="kw">c</span>(<span class="dv">214</span>:<span class="dv">219</span>))
df</code></pre></div>
<pre class="output"><code> id x y
1 a 1 214
2 b 2 215
3 c 3 216
4 d 4 217
5 e 5 218
6 f 6 219
</code></pre>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge-1-data-frames"><span class="glyphicon glyphicon-pencil"></span>Challenge 1: Data frames</h2>
</div>
<div class="panel-body">
<p>Try using the <code>length</code> function to query your data frame <code>df</code>. Does it give the result you expect?</p>
</div>
</section>
<p>Each column in the data frame is simply a list element, which is why when you ask for the <code>length</code> of the data frame, it tells you the number of columns. If you actually want the number of rows, you can use the <code>nrow</code> function.</p>
<p>We can add columns or rows to a data.frame using <code>cbind</code> or <code>rbind</code> (these are the two-dimensional equivalents of the <code>c</code> function):</p>
<h2 id="adding-columns-to-a-data-frame">Adding columns to a data frame</h2>
<p>To add a column we can use <code>cbind</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">cbind</span>(df, <span class="dv">6</span>:<span class="dv">1</span>)
df</code></pre></div>
<pre class="output"><code> id x y 6:1
1 a 1 214 6
2 b 2 215 5
3 c 3 216 4
4 d 4 217 3
5 e 5 218 2
6 f 6 219 1
</code></pre>
<p>Note that R automatically names the column. We may decide to change the name by assigning a value using the <code>names</code> function:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">names</span>(df)[<span class="dv">4</span>] <-<span class="st"> 'SixToOne'</span></code></pre></div>
<p>We can also provide a name when we add the column:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">cbind</span>(df, <span class="dt">caps=</span>LETTERS[<span class="dv">1</span>:<span class="dv">6</span>])
df</code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
</code></pre>
<p>(<code>LETTERS</code> and <code>letters</code> are built-in constants.)</p>
<h2 id="adding-rows-to-a-data-frame">Adding rows to a data frame</h2>
<p>To add a row we use <code>rbind</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">rbind</span>(df, <span class="kw">list</span>(<span class="st">"g"</span>, <span class="dv">11</span>, <span class="dv">42</span>, <span class="dv">0</span>, <span class="st">"G"</span>))</code></pre></div>
<pre class="error"><code>Warning in `[<-.factor`(`*tmp*`, ri, value = "g"): invalid factor level, NA
generated
</code></pre>
<pre class="error"><code>Warning in `[<-.factor`(`*tmp*`, ri, value = "G"): invalid factor level, NA
generated
</code></pre>
<p>Note that we add the row as a list, because we have multiple types across the columns. Nevertheless, this doesn’t work as expected! What do the error messages tell us?</p>
<p>It appears that R was trying to append “g” and “G” as factor levels. Why? Let’s examine the first column. We can access a column in a <code>data.frame</code> by using the <code>$</code> operator.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">class</span>(df$id)</code></pre></div>
<pre class="output"><code>[1] "factor"
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(df)</code></pre></div>
<pre class="output"><code>'data.frame': 7 obs. of 5 variables:
$ id : Factor w/ 6 levels "a","b","c","d",..: 1 2 3 4 5 6 NA
$ x : num 1 2 3 4 5 6 11
$ y : num 214 215 216 217 218 219 42
$ SixToOne: num 6 5 4 3 2 1 0
$ caps : Factor w/ 6 levels "A","B","C","D",..: 1 2 3 4 5 6 NA
</code></pre>
<p>When we created the data frame, R automatically made the first and last columns into factors, not character vectors. There are no pre-existing levels “g” and “G”, so the attempt to add these values fails. A row was added to the data frame, only there are missing values in the factor columns:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df</code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
7 <NA> 11 42 0 <NA>
</code></pre>
<p>There are two ways we can work around this issue:</p>
<ol style="list-style-type: decimal">
<li><p>We can convert the factor columns into characters. This is convenient, but we lose the factor structure.</p></li>
<li><p>We can add factor levels to accomodate the new additions. If we really do want the columns to be factors, this is the correct way to proceed.</p></li>
</ol>
<p>We will illustrate both solutions in the same data frame:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df$id <-<span class="st"> </span><span class="kw">as.character</span>(df$id) <span class="co"># convert to character</span>
<span class="kw">class</span>(df$id)</code></pre></div>
<pre class="output"><code>[1] "character"
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">levels</span>(df$caps) <-<span class="st"> </span><span class="kw">c</span>(<span class="kw">levels</span>(df$caps), <span class="st">'G'</span>) <span class="co"># add a factor level</span>
<span class="kw">class</span>(df$caps)</code></pre></div>
<pre class="output"><code>[1] "factor"
</code></pre>
<p>Okay, now let’s try adding that row again.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">rbind</span>(df, <span class="kw">list</span>(<span class="st">"g"</span>, <span class="dv">11</span>, <span class="dv">42</span>, <span class="dv">0</span>, <span class="st">'G'</span>))
<span class="kw">tail</span>(df, <span class="dt">n=</span><span class="dv">3</span>)</code></pre></div>
<pre class="output"><code> id x y SixToOne caps
6 f 6 219 1 F
7 <NA> 11 42 0 <NA>
8 g 11 42 0 G
</code></pre>
<p>We successfully added the last row, but we have an undesired row with two <code>NA</code> values. How do delete it?</p>
<h2 id="deleting-rows-and-handling-na">Deleting rows and handling NA</h2>
<p>There are multiple ways to delete a row containing <code>NA</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df[-<span class="dv">7</span>, ] <span class="co"># The minus sign tells R to delete the row</span></code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
8 g 11 42 0 G
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df[<span class="kw">complete.cases</span>(df), ] <span class="co"># Return `TRUE` when no missing values</span></code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
8 g 11 42 0 G
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">na.omit</span>(df) <span class="co"># Another function for the same purpose</span></code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
8 g 11 42 0 G
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df <-<span class="st"> </span><span class="kw">na.omit</span>(df)</code></pre></div>
<h2 id="combining-data-frames">Combining data frames</h2>
<p>We can also row-bind data.frames together, but notice what happens to the rownames:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rbind</span>(df, df)</code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
8 g 11 42 0 G
11 a 1 214 6 A
21 b 2 215 5 B
31 c 3 216 4 C
41 d 4 217 3 D
51 e 5 218 2 E
61 f 6 219 1 F
81 g 11 42 0 G
</code></pre>
<p>R is making sure that rownames are unique. You can restore sequential numbering by setting rownames to NULL:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">df2 <-<span class="st"> </span><span class="kw">rbind</span>(df, df)
<span class="kw">rownames</span>(df2) <-<span class="st"> </span><span class="ot">NULL</span>
df2</code></pre></div>
<pre class="output"><code> id x y SixToOne caps
1 a 1 214 6 A
2 b 2 215 5 B
3 c 3 216 4 C
4 d 4 217 3 D
5 e 5 218 2 E
6 f 6 219 1 F
7 g 11 42 0 G
8 a 1 214 6 A
9 b 2 215 5 B
10 c 3 216 4 C
11 d 4 217 3 D
12 e 5 218 2 E
13 f 6 219 1 F
14 g 11 42 0 G
</code></pre>
<!--
When we add a row we need to use a list, because each column is
a different type! If you want to add multiple rows to a data.frame,
you will need to separate the new columns in the list:
~~~{.r}
df <- rbind(df, list(c("l", "m"), c(12, 13), c(534, -20), c(-1, -2),
c('H', 'I')))
~~~
~~~{.error}
Warning in `[<-.factor`(`*tmp*`, ri, value = c("H", "I")): invalid factor
level, NA generated
~~~
~~~{.r}
tail(df, n=3)
~~~
~~~{.output}
id x y SixToOne caps
8 g 11 42 0 G
81 l 12 534 -1 <NA>
9 m 13 -20 -2 <NA>
~~~
-->
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge-2"><span class="glyphicon glyphicon-pencil"></span>Challenge 2</h2>
</div>
<div class="panel-body">
<p>Create a data frame that holds the following information for yourself:</p>
<ul>
<li>First name</li>
<li>Last name</li>
<li>Age</li>
</ul>
<p>Then use rbind to add the same information for the people sitting near you.</p>
<p>Now use cbind to add a column of logicals that will, for each person, hold the answer to the question, “Is there anything in this workshop you’re finding confusing?”</p>
</div>
</section>
<h2 id="reading-in-data">Reading in data</h2>
<p>Remember earlier we obtained the gapminder dataset. If you’re curious about where this data comes from you might like to look at the <a href="http://www.gapminder.org/data/documentation/">Gapminder website</a>.</p>
<p>Now we want to load the gapminder data into R. Before reading in data, it’s a good idea to have a look at its structure. Let’s take a look using our newly-learned shell skills:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">cd data/<span class="st"> </span><span class="co"># navigate to the data directory of the project folder</span>
head gapminder-FiveYearData.csv</code></pre></div>
<pre class="output"><code>country,year,pop,continent,lifeExp,gdpPercap
Afghanistan,1952,8425333,Asia,28.801,779.4453145
Afghanistan,1957,9240934,Asia,30.332,820.8530296
Afghanistan,1962,10267083,Asia,31.997,853.10071
Afghanistan,1967,11537966,Asia,34.02,836.1971382
Afghanistan,1972,13079460,Asia,36.088,739.9811058
Afghanistan,1977,14880372,Asia,38.438,786.11336
Afghanistan,1982,12881816,Asia,39.854,978.0114388
Afghanistan,1987,13867957,Asia,40.822,852.3959448
Afghanistan,1992,16317921,Asia,41.674,649.3413952
</code></pre>
<p>As its file extension would suggest, the file contains comma-separated values, and seems to contain a header row.</p>
<p>We can use <code>read.table</code> to read this into R</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">gapminder <-<span class="st"> </span><span class="kw">read.table</span>(
<span class="dt">file=</span><span class="st">"data/gapminder-FiveYearData.csv"</span>,
<span class="dt">header=</span><span class="ot">TRUE</span>, <span class="dt">sep=</span><span class="st">","</span>
)
<span class="kw">head</span>(gapminder)</code></pre></div>
<pre class="output"><code> country year pop continent lifeExp gdpPercap
1 Afghanistan 1952 8425333 Asia 28.801 779.4453
2 Afghanistan 1957 9240934 Asia 30.332 820.8530
3 Afghanistan 1962 10267083 Asia 31.997 853.1007
4 Afghanistan 1967 11537966 Asia 34.020 836.1971
5 Afghanistan 1972 13079460 Asia 36.088 739.9811
6 Afghanistan 1977 14880372 Asia 38.438 786.1134
</code></pre>
<p>Because we know the structure of the data, we’re able to specify the appropriate arguments to <code>read.table</code>. Without these arguments, <code>read.table</code> will do its best to do something sensible, but it is always more reliable to explicitly tell <code>read.table</code> the structure of the data. <code>read.csv</code> function provides a convenient shortcut for loading in CSV files.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Here is the read.csv version of the above command</span>
gapminder <-<span class="st"> </span><span class="kw">read.csv</span>(
<span class="dt">file=</span><span class="st">"data/gapminder-FiveYearData.csv"</span>
)
<span class="kw">head</span>(gapminder)</code></pre></div>
<pre class="output"><code> country year pop continent lifeExp gdpPercap
1 Afghanistan 1952 8425333 Asia 28.801 779.4453
2 Afghanistan 1957 9240934 Asia 30.332 820.8530
3 Afghanistan 1962 10267083 Asia 31.997 853.1007
4 Afghanistan 1967 11537966 Asia 34.020 836.1971
5 Afghanistan 1972 13079460 Asia 36.088 739.9811
6 Afghanistan 1977 14880372 Asia 38.438 786.1134
</code></pre>
<aside class="callout panel panel-info">
<div class="panel-heading">
<h2 id="miscellaneous-tips"><span class="glyphicon glyphicon-pushpin"></span>Miscellaneous Tips</h2>
</div>
<div class="panel-body">
<ol style="list-style-type: decimal">
<li><p>Another type of file you might encounter are tab-separated format. To specify a tab as a separator, use <code>"\t"</code>.</p></li>
<li><p>You can also read in files from the Internet by replacing the file paths with a web address.</p></li>
<li><p>You can read directly from excel spreadsheets without converting them to plain text first by using the <code>xlsx</code> package.</p></li>
</ol>
</div>
</aside>
<p>To make sure our analysis is reproducible, we should put the code into a script file so we can come back to it later.</p>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge-3"><span class="glyphicon glyphicon-pencil"></span>Challenge 3</h2>
</div>
<div class="panel-body">
<p>Go to file -> new file -> R script, and write an R script to load in the gapminder dataset. Put it in the <code>scripts/</code> directory.</p>
<p>Run the script using the <code>source</code> function, using the file path as its argument (or by pressing the “source” button in RStudio).</p>
</div>
</section>
<h2 id="using-data-frames-the-gapminder-dataset">Using data frames: the <code>gapminder</code> dataset</h2>
<p>To recap what we’ve just learned, let’s have a look at our example data (life expectancy in various countries for various years).</p>
<p>Remember, there are a few functions we can use to interrogate data structures in R:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">class</span>() <span class="co"># what is the data structure?</span>
<span class="kw">typeof</span>() <span class="co"># what is its atomic type?</span>
<span class="kw">length</span>() <span class="co"># how long is it? What about two dimensional objects?</span>
<span class="kw">attributes</span>() <span class="co"># does it have any metadata?</span>
<span class="kw">str</span>() <span class="co"># A full summary of the entire object</span>
<span class="kw">dim</span>() <span class="co"># Dimensions of the object - also try nrow(), ncol()</span></code></pre></div>
<p>Let’s use them to explore the gapminder dataset.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">typeof</span>(gapminder)</code></pre></div>
<pre class="output"><code>[1] "list"
</code></pre>
<p>Remember, data frames are lists ‘under the hood’.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">class</span>(gapminder)</code></pre></div>
<pre class="output"><code>[1] "data.frame"
</code></pre>
<p>The gapminder data is stored in a “data.frame”. This is the default data structure when you read in data, and (as we’ve heard) is useful for storing data with mixed types of columns.</p>
<p>Let’s look at some of the columns.</p>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge-4-data-types-in-a-real-dataset"><span class="glyphicon glyphicon-pencil"></span>Challenge 4: Data types in a real dataset</h2>
</div>
<div class="panel-body">
<p>Look at the first 6 rows of the gapminder data frame we loaded before:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(gapminder)</code></pre></div>
<pre class="output"><code> country year pop continent lifeExp gdpPercap
1 Afghanistan 1952 8425333 Asia 28.801 779.4453
2 Afghanistan 1957 9240934 Asia 30.332 820.8530
3 Afghanistan 1962 10267083 Asia 31.997 853.1007
4 Afghanistan 1967 11537966 Asia 34.020 836.1971
5 Afghanistan 1972 13079460 Asia 36.088 739.9811
6 Afghanistan 1977 14880372 Asia 38.438 786.1134
</code></pre>
<p>Write down what data type you think is in each column</p>
</div>
</section>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">typeof</span>(gapminder$year)</code></pre></div>
<pre class="output"><code>[1] "integer"
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">typeof</span>(gapminder$lifeExp)</code></pre></div>
<pre class="output"><code>[1] "double"
</code></pre>
<p>Can anyone guess what we should expect the type of the continent column to be?</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">typeof</span>(gapminder$continent)</code></pre></div>
<pre class="output"><code>[1] "integer"
</code></pre>
<p>If you were expecting a the answer to be “character”, you would rightly be surprised by the answer. Let’s take a look at the class of this column:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">class</span>(gapminder$continent)</code></pre></div>
<pre class="output"><code>[1] "factor"
</code></pre>
<p>One of the default behaviours of R is to treat any text columns as “factors” when reading in data. The reason for this is that text columns often represent categorical data, which need to be factors to be handled appropriately by the statistical modeling functions in R.</p>
<p>However it’s not obvious behaviour, and something that trips many people up. We can disable this behaviour and read in the data again.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">options</span>(<span class="dt">stringsAsFactors=</span><span class="ot">FALSE</span>)
gapminder <-<span class="st"> </span><span class="kw">read.table</span>(
<span class="dt">file=</span><span class="st">"data/gapminder-FiveYearData.csv"</span>, <span class="dt">header=</span><span class="ot">TRUE</span>, <span class="dt">sep=</span><span class="st">","</span>
)</code></pre></div>
<p>Remember, if you do turn it off automatic conversion to factors you will need to explicitly convert the variables into factors when running statistical models. This can be useful, because it forces you to think about the question you’re asking, and makes it easier to specify the ordering of the categories.</p>
<p>However there are many in the R community who find it more sensible to leave this as the default behaviour.</p>
<aside class="callout panel panel-info">
<div class="panel-heading">
<h2 id="tip-changing-options"><span class="glyphicon glyphicon-pushpin"></span>Tip: Changing options</h2>
</div>
<div class="panel-body">
<p>When R starts, it runs any code in the file <code>.Rprofile</code> in the project directory. You can make permanent changes to default behaviour by storing the changes in that file. BE CAREFUL, however. If you change R’s default options, programs written by others may not run correctly in your environment and vice versa. For this reason, some argue that most such changes should be in your scripts, where they are visible.</p>
</div>
</aside>
<p>The first thing you should do when reading data in, is check that it matches what you expect, even if the command ran without warnings or errors. The <code>str</code> function, short for “structure”, is really useful for this:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(gapminder)</code></pre></div>
<pre class="output"><code>'data.frame': 1704 obs. of 6 variables:
$ country : chr "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ...
$ year : int 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
$ pop : num 8425333 9240934 10267083 11537966 13079460 ...
$ continent: chr "Asia" "Asia" "Asia" "Asia" ...
$ lifeExp : num 28.8 30.3 32 34 36.1 ...
$ gdpPercap: num 779 821 853 836 740 ...
</code></pre>
<p>We can see that the object is a <code>data.frame</code> with 1,704 observations (rows), and 6 variables (columns). Below that, we see the name of each column, followed by a “:”, followed by the type of variable in that column, along with the first few entries.</p>
<p>As discussed above, we can retrieve or modify the column or row names of the data.frame:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">colnames</span>(gapminder) </code></pre></div>
<pre class="output"><code>[1] "country" "year" "pop" "continent" "lifeExp" "gdpPercap"
</code></pre>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">copy <-<span class="st"> </span>gapminder
<span class="kw">colnames</span>(copy) <-<span class="st"> </span>letters[<span class="dv">1</span>:<span class="dv">6</span>]
<span class="kw">head</span>(copy, <span class="dt">n=</span><span class="dv">3</span>)</code></pre></div>
<pre class="output"><code> a b c d e f
1 Afghanistan 1952 8425333 Asia 28.801 779.4453
2 Afghanistan 1957 9240934 Asia 30.332 820.8530
3 Afghanistan 1962 10267083 Asia 31.997 853.1007
</code></pre>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="challenge-5"><span class="glyphicon glyphicon-pencil"></span>Challenge 5</h2>
</div>
<div class="panel-body">
<p>Recall that we also used the <code>names</code> function (above) to modify column names. Does it matter which you use? You can check help with <code>?names</code> and <code>?colnames</code> to see whether it should matter.</p>
</div>
</section>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rownames</span>(gapminder)[<span class="dv">1</span>:<span class="dv">20</span>]</code></pre></div>
<pre class="output"><code> [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14"
[15] "15" "16" "17" "18" "19" "20"
</code></pre>
<p>See those numbers in the square brackets on the left? That tells you the number of the first entry in that row of output. So we see that for the 5th row, the rowname is “5”. In this case, the rownames are simply the row numbers.</p>
<p>There are a few related ways of retrieving and modifying this information. <code>attributes</code> will give you both the row and column names, along with the class information, while <code>dimnames</code> will give you just the rownames and column names.</p>
<p>In both cases, the output object is stored in a <code>list</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(<span class="kw">dimnames</span>(gapminder))</code></pre></div>
<pre class="output"><code>List of 2
$ : chr [1:1704] "1" "2" "3" "4" ...
$ : chr [1:6] "country" "year" "pop" "continent" ...
</code></pre>
<h2 id="understanding-how-lists-are-used-in-function-output">Understanding how lists are used in function output</h2>
<p>Lets run a basic linear regression on the gapminder dataset:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># What is the relationship between life expectancy and year?</span>
reg <-<span class="st"> </span><span class="kw">lm</span>(lifeExp ~<span class="st"> </span>year, <span class="dt">data=</span>gapminder)</code></pre></div>
<p>We won’t go into too much detail, but briefly:</p>
<ul>
<li><code>lm</code> estimates linear statistical models</li>
<li>The first argument is a formula, with <code>a ~ b</code> meaning that <code>a</code>, the dependent (or response) variable, is a function of <code>b</code>, the independent variable.</li>
<li>We tell <code>lm</code> to use the gapminder data frame, so it knows where to find the variables <code>lifeExp</code> and <code>year</code>.</li>
</ul>
<p>Let’s look at the output:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">reg</code></pre></div>
<pre class="output"><code>
Call:
lm(formula = lifeExp ~ year, data = gapminder)
Coefficients:
(Intercept) year
-585.6522 0.3259
</code></pre>
<p>Not much there right? But if we look at the structure…</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(reg)</code></pre></div>
<pre class="output"><code>List of 12
$ coefficients : Named num [1:2] -585.652 0.326
..- attr(*, "names")= chr [1:2] "(Intercept)" "year"
$ residuals : Named num [1:1704] -21.7 -21.8 -21.8 -21.4 -20.9 ...
..- attr(*, "names")= chr [1:1704] "1" "2" "3" "4" ...
$ effects : Named num [1:1704] -2455.1 232.2 -20.8 -20.5 -20.2 ...
..- attr(*, "names")= chr [1:1704] "(Intercept)" "year" "" "" ...
$ rank : int 2
$ fitted.values: Named num [1:1704] 50.5 52.1 53.8 55.4 57 ...
..- attr(*, "names")= chr [1:1704] "1" "2" "3" "4" ...
$ assign : int [1:2] 0 1
$ qr :List of 5
..$ qr : num [1:1704, 1:2] -41.2795 0.0242 0.0242 0.0242 0.0242 ...
.. ..- attr(*, "dimnames")=List of 2
.. .. ..$ : chr [1:1704] "1" "2" "3" "4" ...
.. .. ..$ : chr [1:2] "(Intercept)" "year"
.. ..- attr(*, "assign")= int [1:2] 0 1
..$ qraux: num [1:2] 1.02 1.03
..$ pivot: int [1:2] 1 2
..$ tol : num 1e-07
..$ rank : int 2
..- attr(*, "class")= chr "qr"
$ df.residual : int 1702
$ xlevels : Named list()
$ call : language lm(formula = lifeExp ~ year, data = gapminder)
$ terms :Classes 'terms', 'formula' length 3 lifeExp ~ year
.. ..- attr(*, "variables")= language list(lifeExp, year)
.. ..- attr(*, "factors")= int [1:2, 1] 0 1
.. .. ..- attr(*, "dimnames")=List of 2
.. .. .. ..$ : chr [1:2] "lifeExp" "year"
.. .. .. ..$ : chr "year"
.. ..- attr(*, "term.labels")= chr "year"
.. ..- attr(*, "order")= int 1
.. ..- attr(*, "intercept")= int 1
.. ..- attr(*, "response")= int 1
.. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
.. ..- attr(*, "predvars")= language list(lifeExp, year)
.. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
.. .. ..- attr(*, "names")= chr [1:2] "lifeExp" "year"
$ model :'data.frame': 1704 obs. of 2 variables:
..$ lifeExp: num [1:1704] 28.8 30.3 32 34 36.1 ...
..$ year : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
..- attr(*, "terms")=Classes 'terms', 'formula' length 3 lifeExp ~ year
.. .. ..- attr(*, "variables")= language list(lifeExp, year)
.. .. ..- attr(*, "factors")= int [1:2, 1] 0 1
.. .. .. ..- attr(*, "dimnames")=List of 2
.. .. .. .. ..$ : chr [1:2] "lifeExp" "year"
.. .. .. .. ..$ : chr "year"
.. .. ..- attr(*, "term.labels")= chr "year"
.. .. ..- attr(*, "order")= int 1
.. .. ..- attr(*, "intercept")= int 1
.. .. ..- attr(*, "response")= int 1
.. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
.. .. ..- attr(*, "predvars")= language list(lifeExp, year)
.. .. ..- attr(*, "dataClasses")= Named chr [1:2] "numeric" "numeric"
.. .. .. ..- attr(*, "names")= chr [1:2] "lifeExp" "year"
- attr(*, "class")= chr "lm"
</code></pre>
<p>There’s a great deal stored in nested lists! The structure function allows you to see all the data available, in this case, the data that was returned by the <code>lm</code> function.</p>
<p>For now, we can look at the <code>summary</code>:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">summary</span>(reg)</code></pre></div>
<pre class="output"><code>
Call:
lm(formula = lifeExp ~ year, data = gapminder)
Residuals:
Min 1Q Median 3Q Max
-39.949 -9.651 1.697 10.335 22.158
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -585.65219 32.31396 -18.12 <2e-16 ***
year 0.32590 0.01632 19.96 <2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 11.63 on 1702 degrees of freedom
Multiple R-squared: 0.1898, Adjusted R-squared: 0.1893
F-statistic: 398.6 on 1 and 1702 DF, p-value: < 2.2e-16
</code></pre>
<p>As you might expect, life expectancy has slowly been increasing over time, so we see a significant positive association!</p>
<h2 id="challenge-solutions">Challenge Solutions</h2>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="solution-to-challenge-2"><span class="glyphicon glyphicon-pencil"></span>Solution to Challenge 2</h2>
</div>
<div class="panel-body">
<p>Create a data frame that holds the following information for yourself:</p>
<ul>
<li>First name</li>
<li>Last name</li>
<li>Age</li>
</ul>
<p>Then use rbind to add the same information for the people sitting near you.</p>
<p>Now use cbind to add a column of logicals answering the question, “Is there anything in this workshop you’re finding confusing?”</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">my_df <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">first_name =</span> <span class="st">"Software"</span>, <span class="dt">last_name =</span> <span class="st">"Carpentry"</span>, <span class="dt">age =</span> <span class="dv">17</span>)
my_df <-<span class="st"> </span><span class="kw">rbind</span>(my_df, <span class="kw">list</span>(<span class="st">"Jane"</span>, <span class="st">"Smith"</span>, <span class="dv">29</span>))
my_df <-<span class="st"> </span><span class="kw">rbind</span>(my_df, <span class="kw">list</span>(<span class="kw">c</span>(<span class="st">"Jo"</span>, <span class="st">"John"</span>), <span class="kw">c</span>(<span class="st">"White"</span>, <span class="st">"Lee"</span>), <span class="kw">c</span>(<span class="dv">23</span>, <span class="dv">41</span>)))
my_df <-<span class="st"> </span><span class="kw">cbind</span>(my_df, <span class="dt">confused =</span> <span class="kw">c</span>(<span class="ot">FALSE</span>, <span class="ot">FALSE</span>, <span class="ot">TRUE</span>, <span class="ot">FALSE</span>))</code></pre></div>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2 id="solution-to-challenge-5"><span class="glyphicon glyphicon-pencil"></span>Solution to Challenge 5</h2>
</div>
<div class="panel-body">
<p><code>?colnames</code> tells you that the <code>colnames</code> function is the same as <code>names</code> for a data frame. For other structures, they may not be the same. In particular, <code>names</code> does not work for matrices, but <code>colnames</code> does. You can verify this with</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">m <-<span class="st"> </span><span class="kw">matrix</span>(<span class="dv">1</span>:<span class="dv">9</span>, <span class="dt">nrow=</span><span class="dv">3</span>)
<span class="kw">colnames</span>(m) <-<span class="st"> </span>letters[<span class="dv">1</span>:<span class="dv">3</span>] <span class="co"># works as you would expect</span>
<span class="kw">names</span>(m) <-<span class="st"> </span>letters[<span class="dv">1</span>:<span class="dv">3</span>] <span class="co"># destroys the matrix</span></code></pre></div>
</div>
</section>
</div>
</div>
</article>
<div class="footer">
<a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
<a class="label swc-blue-bg" href="https://github.com/swcarpentry/lesson-template">Source</a>
<a class="label swc-blue-bg" href="mailto:[email protected]">Contact</a>
<a class="label swc-blue-bg" href="LICENSE.html">License</a>
</div>
</div>
<!-- Javascript placed at the end of the document so the pages load faster -->
<script src="http://software-carpentry.org/v5/js/jquery-1.9.1.min.js"></script>
<script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
</body>
</html>