-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseRTipsandTricks.Rmd
More file actions
566 lines (448 loc) · 8.51 KB
/
Copy pathBaseRTipsandTricks.Rmd
File metadata and controls
566 lines (448 loc) · 8.51 KB
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
---
title: "SCC: Some tips & tricks using Base-R"
subtitle: "with a focus on data manipulation"
author: "Jeroen Minderman (jeroen.minderman2@stir.ac.uk)"
date: "<br><br><br><br><br><br><br>26 September 2019 (<i>updated: `r format(Sys.Date(),'%d/%m/%y')`</i>)"
output:
xaringan::moon_reader:
css: ["default", "metropolis_jm.css", "metropolis_jm-fonts.css"]
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
titleSlideClass: [top, left]
---
``` {r echo=FALSE}
library(knitr)
```
# "Base-R"
## Wot now?
https://stat.ethz.ch/R-manual/R-devel/library/base/DESCRIPTION
```html
Package: base
Version: 3.7.0
Priority: base
Title: The R Base Package
Author: R Core Team and contributors worldwide
Maintainer: R Core Team <R-core@r-project.org>
Description: Base R functions.
License: Part of R 3.7.0
Suggests: methods
Built: R 3.7.0; ; Mon Sep 23 01:12:01 UTC 2019; unix
```
"Base-R": the R functionality you get on first installation, without any extra packages
---
# What *"extra packages"* be this?
## Tonnes of options for data wrangling in R
--

---
class: inverse, center, middle

---
# So why use Base-R?
.left-column[
]
.right-column[
{{content}}
]
--
- You are a masochist

---
# So why use Base-R?
.left-column[
]
.right-column[
{{content}}
]
--
- You are a masochist
{{content}}
--
- You like to know the basics
{{content}}
--
- You like to be flexible
{{content}}
--
- Backwards "portability" (?)
{{content}}
--
- You prefer "base R" coding style
{{content}}
--
- **Not reliant on "third party" packages**
{{content}}
--
**Basically, it's a matter of ___preference___... **
{{content}}
--
*..but there are some advantages!*
---
# Session outline
.left-column[
]
.right-column[
{{content}}
]
--
Just a few examples of handy functions for data wrangling in base-R...
{{content}}
--
1. Matrices, dataframes, indexing (a *very brief* recap)
{{content}}
--
2. Using *match()* to merge data frames
{{content}}
--
3. Doing stuff with rows and columns: *apply()*
{{content}}
--
4. Doing stuff with factors: *tapply()*
{{content}}
--
5. Lists and doing stuff to them: *lapply()*
{{content}}
--
6. ?
{{content}}
**Health warning:** your mileage (and methods) may vary.
This is just one way, and one I like using.
---
#Matrices, dataframes, indexing (1)
##"Row, Column"
- So, .content-box-red[`df1[i,j]`] = row *i* and column *j* from data frame (or matrix) *df1*.
- Leaving one of the indexes blank means return "all"
.pull-left[
```{r echo=F}
df1 <- data.frame(c1=c("a","b","c"),c2=c(1,2,3))
```
```{r}
df1
```
]
--
.pull-right[
```{r}
df1[1,]
```
```{r}
df1[,2]
```
]
---
#Matrices, dataframes, indexing (2)
##Indexing works on both **matrices** and dataframes.
- Matrices are just tables of numbers
- So you can think of them of matrices in the mathematical sense
.pull-left[
```{r echo=F}
mat1 <- matrix(c(1,2,3,4), nrow=2, ncol = 2)
```
```{r}
mat1
mat1[1,]
```
]
--
.pull-right[
```{r}
eigen(mat1)$values
mat1[1,] %*% mat1[2,]
```
]
---
#Matrices, dataframes, indexing (3)
##Indexing works on both matrices and **dataframes**.
- Dataframes are matrices with a few more features
- They (can) have descriptive row- and column names
- They can have columns with different data types
.pull-left[
```{r echo=F}
df2 <- data.frame(id=c("A","B","C"), measure = c(1.1,2.2,3.3))
row.names(df2) <- c("row1","row2","row3")
```
```{r}
df2
df2[2,]
```
]
--
.pull-right[
Calculus doesn't (always) work...
```{r eval=F}
eigen(df2)
```
But you can express (numeric) dataframes as matrices or vice versa:
```{r}
df3 <- as.data.frame(mat1)
```
]
---
#Matrices, dataframes, indexing (4)
##Dataframes - indexing by column- or row names
.pull-left[
```{r}
df2
names(df2)
row.names(df2)
```
]
--
.pull-right[
```{r, eval=F}
df2[,2]
df2$measure
df2[,"measure"]
```
```{r, echo=F}
df2[,2]
```
]
---
#Matrices, dataframes, indexing (5)
##Dataframes - more uses of column/row names
.pull-left[
```{r}
df2
names(df2)
names(df2) <- c("indiv","val")
df2
```
]
--
.pull-right[
**Adding a column**
```{r}
df2$newcol <- c(7.0,7.3,7.9)
df2
```
**Removing a column**:
```{r}
df2$val <- NULL
df2
```
]
---
#Using _match()_ to merge data frames (1)
##Now for something more interesting..!
- `match()` matches values from one vector to values from another.
- We can use this to "match up" data from one dataframe to another (equivalent of "merge" or "joins").
.pull-left[
```{r}
df2
```
]
--
.pull-right[
```{r, echo=F}
df3 <- data.frame(id = c("B","B","C","C"), multimeasure = c(81,87,91,93))
```
```{r}
df3
```
]
.content-box-red[
We want to insert 'ncol' values for each 'indiv' from dataframe `df2` into dataframe `df3`, by individual identifier.
]
---
#Using _match()_ to merge data frames (2)
.pull-left[
```{r}
df3
```
]
.pull-right[
```{r}
df2
```
]
--
```{r, eval=F}
df3$newcol <- df2$newcol[match(df3$id, df2$indiv)]
```
--
.center[
```{r, echo=F}
df3$newcol <- df2$newcol[match(df3$id, df2$indiv)]
```
```{r}
df3
```
]
---
# Working with rows and columns: _apply()_ (1)
The `apply()` function takes a dataframe/matrix and "applies" a function to one of its dimensions: rows, or columns.
```{r echo=F}
df4 <- data.frame(col1 = c(1.1,2.1,3.1), col2 = c(4.2,5.2,6.2))
```
.center[
```{r}
df4
```
Rows, columns...
]
--
.pull-left[
**Row means** (rows = 1)
```{r}
apply(df4, 1, mean)
```
]
--
.pull-right[
**Column medians** (row = 2)
```{r}
apply(df4, 2, median)
```
]
---
# Working with rows and columns: _apply()_ (2)
`apply()` works with custom functions, too!
.pull-left[
```{r}
df4[2,2] <- NA
df4
```
```{r}
apply(df4, 2, mean)
```
]
--
.pull-right[
```{r}
mean_no_na <- function(x) {
return(mean(x, na.rm=T))
}
apply(df4, 2, mean_no_na)
```
]
---
# Working with factors: _tapply()_ (1)
- `tapply()` is similar to apply() but can apply a function to a vector while subsetting using another vector
- This is useful for calculating group means, for example.
.pull-left[
```{r}
df3
```
]
--
.pull-right[
```{r}
df3$id
```
]
--
.center[
```{r}
tapply(df3$multimeasure, df3$id, mean)
```
]
---
# Working with factors: _tapply()_ (2)
- What if we want to add the individual means to the table?
- One option is to use `tapply()` to both calculate both means and the number of measures per group (using `length()`)
- Then use `rep()` to create a new column
```{r}
id_means <- tapply(df3$multimeasure, df3$id, mean)
id_obs <- tapply(df3$multimeasure, df3$id, length)
```
--
.left-column[
```{r}
id_means
id_obs
```
]
--
.right-column[
```{r}
means_col <- rep(id_means, id_obs)
df3$means_col <- means_col
df3
```
]
---
# Working with lists: _lapply()_ (1)
- Lists are collections of other objects, e.g. matrices or dataframes.
- They are convenient in e.g. working with more than "two dimensions"
```{r, echo=F}
names(df2) <- c("id","c2")
names(df3) <- c("id","c1","c2","c3")
```
```{r}
mylist <- list(df2, df3)
mylist
```
---
# Working with lists: _lapply()_ (2)
- They can be indexed in the same way as matrices/DF's, but using double square brackets`[[i]]`
.pull-left[
```{r}
mylist[[1]]
mylist[[1]][1,]
```
]
--
.pull-right[
```{r}
mylist[[2]]
mylist[[2]][,1]
```
]
---
# Working with lists: _lapply()_ (3)
- Lists can also be named
```{r}
names(mylist) <- c("element1", "element2")
```
.pull-left[
```{r}
mylist
```
]
--
.pull-right[
```{r, eval=F}
mylist[[2]]
mylist[["element2"]]
```
```{r}
mylist$element2
```
]
---
# Working with lists: _lapply()_ (4)
- Finally, `lapply()` can be used to apply functions to (elements of) lists.
- Only two arguments, the name of the list and the function to apply.
- Simple example, find the column names (`names(`) for each list element:
```{r}
lapply(mylist, names)
```
---
# Working with lists: _lapply()_ (5)
This is far more interesting when using custom functions.
For example, calculate the mean for column `c2` in each list element:
.pull-left[
```{r}
mylist
```
]
--
.pull-right[
```{r}
c2_mean <- function(x) {
return(mean(x$c2))
}
lapply(mylist, c2_mean)
```
]
---
class: inverse, center, middle

# Wanna play?
[https://stirlingcodingclub.github.io/Base-R/Base-R-practice.html](https://stirlingcodingclub.github.io/Base-R/Base-R-practice.html)
or the Github repo itself:
[https://github.com/StirlingCodingClub/Base-R](https://github.com/StirlingCodingClub/Base-R)