forked from kbroman/datacarpentry_R_2017-01-10
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-notes.html
530 lines (485 loc) · 25.4 KB
/
01-notes.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Data Carpentry contributors" />
<title>Intro to R (notes)</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="libs/navigation-1.1/tabsets.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; background-color: #f8f8f8; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
pre, code { background-color: #f8f8f8; }
code > span.kw { color: #204a87; font-weight: bold; }
code > span.dt { color: #204a87; }
code > span.dv { color: #0000cf; }
code > span.bn { color: #0000cf; }
code > span.fl { color: #0000cf; }
code > span.ch { color: #4e9a06; }
code > span.st { color: #4e9a06; }
code > span.co { color: #8f5902; font-style: italic; }
code > span.ot { color: #8f5902; }
code > span.al { color: #ef2929; }
code > span.fu { color: #000000; }
code > span.er { font-weight: bold; }
</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
h1 {
font-size: 34px;
}
h1.title {
font-size: 38px;
}
h2 {
font-size: 30px;
}
h3 {
font-size: 24px;
}
h4 {
font-size: 18px;
}
h5 {
font-size: 16px;
}
h6 {
font-size: 12px;
}
.table th:not([align]) {
text-align: left;
}
</style>
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Intro to R (notes)</h1>
<h4 class="author"><em>Data Carpentry contributors</em></h4>
</div>
<div id="TOC">
<ul>
<li><a href="#r-and-rstudio">R and RStudio</a><ul>
<li><a href="#r">R</a></li>
<li><a href="#rstudio">RStudio</a></li>
<li><a href="#rstudio-orientation">RStudio orientation</a></li>
</ul></li>
<li><a href="#r-as-a-calculator">R as a calculator</a></li>
<li><a href="#getting-help">Getting help</a></li>
<li><a href="#need-for-scripts">Need for scripts</a><ul>
<li><a href="#create-a-new-r-project">Create a new R project</a></li>
<li><a href="#create-an-r-script">Create an R script</a></li>
</ul></li>
<li><a href="#typing-into-the-script-and-pasting-to-console">Typing into the script and pasting to console</a></li>
<li><a href="#assigment-operator">Assigment operator</a><ul>
<li><a href="#using-the-stuff-you-assigned">Using the stuff you assigned</a></li>
<li><a href="#object-names">Object names</a></li>
<li><a href="#named-arguments">Named arguments</a></li>
<li><a href="#challenge">Challenge</a></li>
</ul></li>
<li><a href="#plunge-into-survey-data">Plunge into Survey Data</a><ul>
<li><a href="#objects-in-workspace">Objects in workspace</a></li>
</ul></li>
<li><a href="#data-frames">Data frames</a><ul>
<li><a href="#challenge-1">Challenge</a></li>
<li><a href="#another-summary">Another summary</a></li>
</ul></li>
<li><a href="#inspecting-data-frames">Inspecting data frames</a></li>
<li><a href="#download-and-then-load-the-data">Download and then load the data</a></li>
<li><a href="#indexing-sequences-and-subsetting">Indexing, Sequences, and Subsetting</a><ul>
<li><a href="#slices">Slices</a></li>
<li><a href="#challenge-2">Challenge</a></li>
</ul></li>
<li><a href="#missing-data">Missing data</a><ul>
<li><a href="#treating-blanks-as-missing">Treating blanks as missing</a></li>
</ul></li>
<li><a href="#factors">Factors</a><ul>
<li><a href="#converting-factors">Converting factors</a></li>
<li><a href="#challenge-3">Challenge</a></li>
<li><a href="#stringsasfactors">stringsAsFactors</a></li>
</ul></li>
</ul>
</div>
<div id="r-and-rstudio" class="section level2">
<h2>R and RStudio</h2>
<div id="r" class="section level3">
<h3>R</h3>
<ul>
<li>Free and open source general statistical programming language</li>
<li>Broad statistical and graphics functions</li>
<li>Huge community of add-on packages</li>
<li>Not just for statistics, but also general purpose programming.</li>
</ul>
</div>
<div id="rstudio" class="section level3">
<h3>RStudio</h3>
<ul>
<li>Integrated Development Environment (IDE) for R</li>
<li>Separate program, developed by a company but also free and open source.</li>
<li>By far the best thing to use when learning R.</li>
</ul>
</div>
<div id="rstudio-orientation" class="section level3">
<h3>RStudio orientation</h3>
<p>Four panes (can be re-organized, but always these four panes)</p>
<ul>
<li>Scripts (top-left)</li>
<li>R console (bottom-left)</li>
<li>Environment/history (top-right)</li>
<li>Files/plots/help/etc (bottom-right)</li>
</ul>
</div>
</div>
<div id="r-as-a-calculator" class="section level2">
<h2>R as a calculator</h2>
<ul>
<li><code>Ctrl-Shift-2</code> to focus only on the R console.</li>
<li><p><code>Ctrl-Shift-0</code> to get back.</p></li>
<li><p>Explain <code>></code> prompt and do some calculations</p></li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r"><span class="dv">2016</span> -<span class="st"> </span><span class="dv">1969</span></code></pre>
<pre><code>## [1] 47</code></pre>
<pre class="sourceCode r"><code class="sourceCode r"><span class="dv">4</span>*<span class="dv">6</span>
<span class="dv">4</span>/<span class="dv">6</span>
<span class="dv">4</span>^<span class="dv">6</span>
<span class="kw">log</span>(<span class="dv">4</span>)
<span class="kw">log10</span>(<span class="dv">4</span>)</code></pre>
<ul>
<li>Explain that <code>log</code> is a function with two arguments.</li>
</ul>
</div>
<div id="getting-help" class="section level2">
<h2>Getting help</h2>
<ul>
<li>Pause for a moment after typing <code>log</code></li>
<li>Type <code>?log</code></li>
</ul>
</div>
<div id="need-for-scripts" class="section level2">
<h2>Need for scripts</h2>
<ul>
<li>Want to save what we’re doing</li>
<li>Really want to organize the scripts and data for a project</li>
</ul>
<div id="create-a-new-r-project" class="section level3">
<h3>Create a new R project</h3>
<ul>
<li>File → New Project → Existing directory → Browse for folder → Create project</li>
</ul>
</div>
<div id="create-an-r-script" class="section level3">
<h3>Create an R script</h3>
<ul>
<li>File → New File → R script</li>
<li>Save it in the <code>Code/</code> directory, <code>data-carpentry-script.R</code></li>
</ul>
</div>
</div>
<div id="typing-into-the-script-and-pasting-to-console" class="section level2">
<h2>Typing into the script and pasting to console</h2>
<ul>
<li>Type some stuff into the script</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r"><span class="co"># R intro</span>
<span class="dv">2016</span> -<span class="st"> </span><span class="dv">1969</span></code></pre>
<ul>
<li><p>Paste to console with <kbd><code>Ctrl</code></kbd> + <kbd><code>Enter</code></kbd></p></li>
<li><p>Explain comment sign, <code>#</code></p></li>
</ul>
</div>
<div id="assigment-operator" class="section level2">
<h2>Assigment operator</h2>
<pre class="sourceCode r"><code class="sourceCode r">age <-<span class="st"> </span><span class="dv">2016</span> -<span class="st"> </span><span class="dv">1969</span></code></pre>
<ul>
<li>Paste into console.</li>
<li>Can also use <code>=</code>, but recommend <code><-</code>.</li>
<li>Can use <kbd>Alt</kbd> + <kbd>-</kbd></li>
</ul>
<div id="using-the-stuff-you-assigned" class="section level3">
<h3>Using the stuff you assigned</h3>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">sqrt</span>(age)</code></pre>
<pre class="sourceCode r"><code class="sourceCode r">sqrt_age <-<span class="st"> </span><span class="kw">sqrt</span>(age)
<span class="kw">round</span>(sqrt_age)
<span class="kw">round</span>(sqrt_age, <span class="dv">2</span>)</code></pre>
</div>
<div id="object-names" class="section level3">
<h3>Object names</h3>
<ul>
<li>explicit but not too long</li>
<li>can’t start with a number</li>
<li>there are some names not allowed (<code>if</code>, <code>for</code>, <code>else</code>)</li>
<li>other names you can but shouldn’t use (<code>c</code>, <code>data</code>, <code>mean</code>)</li>
<li><p>Can use <code>.</code>, but best not to</p></li>
<li><p>Reminder: The last round shows a function with 2 arguments and order matters.</p></li>
</ul>
</div>
<div id="named-arguments" class="section level3">
<h3>Named arguments</h3>
<ul>
<li>Named arguments useful for commands that have lots of them as order can get confusing</li>
<li>Can then switch them</li>
<li>Generally the first argument or two will be entered positionally and then later ones w/name</li>
<li>Names can be found using help methods from earlier</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">round</span>(<span class="dt">x =</span> sqrt_age, <span class="dt">digits =</span> <span class="dv">2</span>)
<span class="kw">round</span>(<span class="dt">digits =</span> <span class="dv">2</span>,<span class="dt">x =</span> sqrt_age)
<span class="kw">round</span>(sqrt_age, <span class="dt">digits =</span> <span class="dv">2</span>)</code></pre>
<ul>
<li>We may occasionally used named arguments in these lessons</li>
</ul>
</div>
<div id="challenge" class="section level3">
<h3>Challenge</h3>
<p>What is the value of <code>y</code> after doing the following?</p>
<pre class="sourceCode r"><code class="sourceCode r">x <-<span class="st"> </span><span class="dv">50</span>
y <-<span class="st"> </span>x *<span class="st"> </span><span class="dv">2</span>
x <-<span class="st"> </span><span class="dv">80</span></code></pre>
<ul>
<li>Objects don’t get linked together</li>
</ul>
</div>
</div>
<div id="plunge-into-survey-data" class="section level2">
<h2>Plunge into Survey Data</h2>
<pre class="sourceCode r"><code class="sourceCode r">surveys <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"http://kbroman.org/datacarp/portal_data_joined.csv"</span>)</code></pre>
<div id="objects-in-workspace" class="section level3">
<h3>Objects in workspace</h3>
<ul>
<li><code>ls()</code></li>
<li>Environment panel</li>
</ul>
</div>
</div>
<div id="data-frames" class="section level2">
<h2>Data frames</h2>
<p>Use <code>head()</code> to view the first few rows.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">head</span>(surveys)</code></pre>
<p>Use <code>tail()</code> to view the last few rows.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">tail</span>(surveys)</code></pre>
<p>Use <code>str()</code> to look at the structure of the data.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(surveys)</code></pre>
<p>Talk about integers and factors; more on factors later.</p>
<div id="challenge-1" class="section level3">
<h3>Challenge</h3>
<p>Study the output of <code>str(surveys)</code>. How are the missing values being treated?</p>
<!-- end challenge -->
</div>
<div id="another-summary" class="section level3">
<h3>Another summary</h3>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">summary</span>(surveys)</code></pre>
<ul>
<li>six-number summary for the numeric columns</li>
<li>table for the factor columns</li>
</ul>
</div>
</div>
<div id="inspecting-data-frames" class="section level2">
<h2>Inspecting data frames</h2>
<ul>
<li><code>dim()</code></li>
<li><code>nrow()</code></li>
<li><code>ncol()</code></li>
<li><code>names()</code></li>
<li><code>colnames()</code></li>
<li><code>rownames()</code></li>
</ul>
</div>
<div id="download-and-then-load-the-data" class="section level2">
<h2>Download and then load the data</h2>
<p>We first download the file:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">download.file</span>(<span class="st">"http://kbroman.org/datacarp/portal_data_joined.csv"</span>,
<span class="st">"CleanData/portal_data_joined.csv"</span>)</code></pre>
<p>We then load them into R:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"CleanData/portal_data_joined.csv"</span>)</code></pre>
</div>
<div id="indexing-sequences-and-subsetting" class="section level2">
<h2>Indexing, Sequences, and Subsetting</h2>
<p>We can pull out parts of a data frame using square brackets. We need to provide two values: row and column, with a comma between them.</p>
<p>For example, to get the element in the 1st row, 1st column:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="dv">1</span>,<span class="dv">1</span>]</code></pre>
<p>To get the element in the 2nd row, 7th column:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="dv">2</span>,<span class="dv">7</span>]</code></pre>
<p>To get the entire 2nd row, leave the column part blank:</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="dv">2</span>,]</code></pre>
<p>And to get the entire 7th column, leave the row part blank:</p>
<pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span>surveys[,<span class="dv">7</span>]</code></pre>
<p>You can also refer to columns by name, in multiple ways.</p>
<pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span>surveys[, <span class="st">"sex"</span>]
sex <-<span class="st"> </span>surveys$sex
sex <-<span class="st"> </span>surveys[[<span class="st">"sex"</span>]]</code></pre>
<p>When we pull out a single column, the result is a “vector”. We can again use square brackets to pull out individual values, but providing a single number.</p>
<pre class="sourceCode r"><code class="sourceCode r">sex[<span class="dv">1</span>]
sex[<span class="dv">10000</span>]</code></pre>
<div id="slices" class="section level3">
<h3>Slices</h3>
<p>You can pull out larger slices from the vector by providing vectors of indices. You can use the <code>c()</code> function to create a vector.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">c</span>(<span class="dv">1</span>,<span class="dv">3</span>,<span class="dv">5</span>)
sex[<span class="kw">c</span>(<span class="dv">1</span>,<span class="dv">3</span>,<span class="dv">5</span>)]</code></pre>
<p>To pull out larger slices, it’s helpful to have ways of creating sequences of numbers.</p>
<p>First, the operator <code>:</code> gives you a sequence of consecutive values.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="dv">1</span>:<span class="dv">10</span>
<span class="dv">10</span>:<span class="dv">1</span>
<span class="dv">5</span>:<span class="dv">8</span></code></pre>
<p><code>seq</code> is more flexible.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">seq</span>(<span class="dv">1</span>, <span class="dv">10</span>, <span class="dt">by=</span><span class="dv">2</span>)
<span class="kw">seq</span>(<span class="dv">5</span>, <span class="dv">10</span>, <span class="dt">length.out=</span><span class="dv">3</span>)
<span class="kw">seq</span>(<span class="dv">50</span>, <span class="dt">by=</span><span class="dv">5</span>, <span class="dt">length.out=</span><span class="dv">10</span>)
<span class="kw">seq</span>(<span class="dv">1</span>, <span class="dv">8</span>, <span class="dt">by=</span><span class="dv">3</span>) <span class="co"># sequence stops to stay below upper limit</span>
<span class="kw">seq</span>(<span class="dv">10</span>, <span class="dv">2</span>, <span class="dt">by=</span>-<span class="dv">2</span>) <span class="co"># can also go backwards</span></code></pre>
<p>To get slices of our data frame, we can include a vector for the row or column indexes (or both)</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys[<span class="dv">1</span>:<span class="dv">3</span>, <span class="dv">7</span>] <span class="co"># first three elements in the 7th column</span>
surveys[<span class="dv">1</span>, <span class="dv">1</span>:<span class="dv">3</span>] <span class="co"># first three columns in the first row</span>
surveys[<span class="dv">2</span>:<span class="dv">4</span>, <span class="dv">6</span>:<span class="dv">7</span>] <span class="co"># rows 2-4, columns 6-7</span></code></pre>
</div>
<div id="challenge-2" class="section level3">
<h3>Challenge</h3>
<p>The function <code>nrow()</code> on a <code>data.frame</code> returns the number of rows.</p>
<p>Use <code>nrow()</code>, in conjuction with <code>seq()</code> to create a new <code>data.frame</code> called <code>surveys_by_10</code> that includes every 10th row of the survey data frame starting at row 10 (10, 20, 30, …)</p>
<!-- end challenge -->
</div>
</div>
<div id="missing-data" class="section level2">
<h2>Missing data</h2>
<p>Missing data value, <code>NA</code>. Different from character string <code>"NA"</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">heights <-<span class="st"> </span><span class="kw">c</span>(<span class="dv">2</span>, <span class="dv">4</span>, <span class="dv">4</span>, <span class="ot">NA</span>, <span class="dv">6</span>)</code></pre>
<p>Many functions will return <code>NA</code> if there is any missing data. Need to use <code>na.rm=TRUE</code> to strip off missing values.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">mean</span>(heights)
<span class="kw">max</span>(heights)
<span class="kw">mean</span>(heights, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)
<span class="kw">max</span>(heights, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>)</code></pre>
<p>If your data include missing values, you may want to become familiar with the functions <code>is.na()</code> and <code>na.omit()</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">## Extract those elements which are not missing values.
heights[!<span class="kw">is.na</span>(heights)]
## shortcut to that
<span class="kw">na.omit</span>(heights)</code></pre>
<div id="treating-blanks-as-missing" class="section level3">
<h3>Treating blanks as missing</h3>
<ul>
<li>blank character strings might be best treated as missing values.</li>
<li>I prefer not to have blank fields, but it’s difficult to choose a universal missing value code.</li>
<li>Use <code>na.strings</code> in <code>read.csv()</code> to indicate missing value codes.</li>
</ul>
<pre class="sourceCode r"><code class="sourceCode r">surveys_noblanks <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"CleanData/portal_data_joined.csv"</span>, <span class="dt">na.strings=</span><span class="st">""</span>)</code></pre>
</div>
</div>
<div id="factors" class="section level2">
<h2>Factors</h2>
<p>Factors represent categorical data. They can be useful, but they can be a pain. And understanding them is necessary for statistical analysis and for plotting.</p>
<p>Factors are stored as integers, and have labels associated with these unique integers. While factors look (and often behave) like character vectors, they are actually integers under the hood, and you need to be careful when treating them like strings.</p>
<p>Once created, factors can only contain a pre-defined set of values, known as <em>levels</em>. By default, R always sorts <em>levels</em> in alphabetical order. For instance, if you use <code>factor()</code> to create a factor with 2 levels:</p>
<pre class="sourceCode r"><code class="sourceCode r">sex <-<span class="st"> </span><span class="kw">factor</span>(<span class="kw">c</span>(<span class="st">"male"</span>, <span class="st">"female"</span>, <span class="st">"female"</span>, <span class="st">"male"</span>))</code></pre>
<p>R will assign <code>1</code> to the level <code>"female"</code> and <code>2</code> to the level <code>"male"</code> (because <code>f</code> comes before <code>m</code>, even though the first element in this vector is <code>"male"</code>). You can check this by using the function <code>levels()</code>, and check the number of levels using <code>nlevels()</code>:</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">levels</span>(sex)
<span class="kw">nlevels</span>(sex)</code></pre>
<p>Sometimes, the order of the factors does not matter, other times you might want to specify a particular order.</p>
<pre class="sourceCode r"><code class="sourceCode r">food <-<span class="st"> </span><span class="kw">factor</span>(<span class="kw">c</span>(<span class="st">"low"</span>, <span class="st">"high"</span>, <span class="st">"medium"</span>, <span class="st">"high"</span>, <span class="st">"low"</span>, <span class="st">"medium"</span>, <span class="st">"high"</span>))
<span class="kw">levels</span>(food)
food <-<span class="st"> </span><span class="kw">factor</span>(food, <span class="dt">levels=</span><span class="kw">c</span>(<span class="st">"low"</span>, <span class="st">"medium"</span>, <span class="st">"high"</span>))
<span class="kw">levels</span>(food)</code></pre>
<div id="converting-factors" class="section level3">
<h3>Converting factors</h3>
<p>If you need to convert a factor to a character vector, you use <code>as.character(x)</code>.</p>
<p>Converting factors where the levels appear as numbers (such as concentration levels) to a numeric vector is a little trickier. One method is to convert factors to characters and then numbers. function. Compare:</p>
<pre class="sourceCode r"><code class="sourceCode r">f <-<span class="st"> </span><span class="kw">factor</span>(<span class="kw">c</span>(<span class="dv">1</span>, <span class="dv">5</span>, <span class="dv">10</span>, <span class="dv">2</span>))
<span class="kw">as.numeric</span>(f) ## wrong! and there is no warning...
<span class="kw">as.numeric</span>(<span class="kw">as.character</span>(f)) ## works...</code></pre>
</div>
<div id="challenge-3" class="section level3">
<h3>Challenge</h3>
<p>The function <code>table()</code> tabulates observations.</p>
<pre class="sourceCode r"><code class="sourceCode r">expt <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"treat1"</span>, <span class="st">"treat2"</span>, <span class="st">"treat1"</span>, <span class="st">"treat3"</span>, <span class="st">"treat1"</span>,
<span class="st">"control"</span>, <span class="st">"treat1"</span>, <span class="st">"treat2"</span>, <span class="st">"treat3"</span>)
expt <-<span class="st"> </span><span class="kw">factor</span>(expt)
<span class="kw">table</span>(expt)</code></pre>
<ul>
<li>In which order are the treatments listed?</li>
<li>How can you recreate this table with “<code>control</code>” listed last instead of first?</li>
</ul>
<!-- end challenge -->
<!---
```r
## Answers
##
## * The treatments are listed in alphabetical order because they are factors.
## * By redefining the order of the levels
expt <- c("treat1", "treat2", "treat1", "treat3", "treat1",
"control", "treat1", "treat2", "treat3")
expt <- factor(expt, levels=c("treat1", "treat2", "treat3", "control"))
table(expt)
```
--->
</div>
<div id="stringsasfactors" class="section level3">
<h3>stringsAsFactors</h3>
<p>The default when reading in data with <code>read.csv()</code>, columns with text get turned into factors.</p>
<p>You can avoid this with the argument <code>stringsAsFactors=FALSE</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r">surveys_chr <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"CleanData/portal_data_joined.csv"</span>, <span class="dt">stringsAsFactors=</span><span class="ot">FALSE</span>)</code></pre>
<p>Then when you look at the result of <code>str()</code>, you’ll see that the previously factor columns are now <code>chr</code>.</p>
<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">str</span>(surveys_chr)</code></pre>
<p><br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/></p>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>