-
Notifications
You must be signed in to change notification settings - Fork 10
/
slide_r_elements_4.Rmd
708 lines (524 loc) · 12.6 KB
/
slide_r_elements_4.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
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
---
title: "Replication, Control Structures & Functions"
subtitle: "Elements of the R language"
author: "Marcin Kierczak, Nima Rafati, Miguel Redondo"
keywords: bioinformatics, course, scilifelab, nbis, R
output:
xaringan::moon_reader:
encoding: 'UTF-8'
self_contained: false
chakra: 'assets/remark-latest.min.js'
css: 'assets/slide.css'
lib_dir: libs
include: NULL
nature:
ratio: '4:3'
highlightLanguage: r
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
slideNumberFormat: "%current%/%total%"
---
exclude: true
count: false
```{r,echo=FALSE,child="assets/header-slide.Rmd"}
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
---
name: contents
# Contents of the lecture
- variables and their types
- operators
- vectors
- matrices
- data frames
- lists
- **repeating actions: loops**
- **decision taking: `if` control structures**
- **functions**
---
name: repeating_actions_1
# Repeating actions
Sometimes you want to repeat certain action several times.
There are few alternatives in R, for example:
- `for` loop
- `while` loop
---
name: for_loop_0
# Repeating actions — for loop
One way to repeat an action is to use the **for-loop**.
This is the general syntax:
```
for (var in seq) {
expr
}
```
Where:
- var = variable that will take values from the sequence
- seq= sequence of values
- expr = expression to be executed
---
name: for_loop_1
# Repeating actions — for loop, an example
Example.
```{r for.loop, echo=T}
for (i in 1:5) {
print(paste('Performing operation on no.', i))
}
```
--
A slight modification of the above example.
```{r for.loop2, echo=T}
for (i in c(2,4,6,8,10)) {
print(paste('Performing operation on no.', i))
}
```
The variable `i` <u> takes values </u> from the sequences.
---
name: for_loop_example
# Repeating actions — for loop, another example
Say, we want to add 1 to every element of a vector:
```{r for.loop.ex1, echo=T}
vec <- c(1:5)
vec
```
```{r for.loop.ex2, echo=T}
for (i in vec) {
vec[i] <- vec[i] + 1
}
vec
```
--
The above can be achieved in R by means of **vectorization**.
**Vectorization** is an element-wise operation where you perform an operation on entire vectors.
```{r for.loop.avoid, echo=T}
vec <- c(1:5)
vec + 1
```
---
name: vectorization_benchmark
exclude:true
# Repeating actions — vectorization
Let us compare the time of execution of the vectorized version (vector with 10,000 elements):
```{r for.loop.avoid.timing, echo=T}
vec <- c(1:1e6)
ptm <- proc.time()
vec <- vec + 1
proc.time() - ptm # vectorized
```
to the loop version:
```{r for.loop.avoid.timing2, echo=T}
vec <- c(1:1e6)
ptm <- proc.time()
for (i in vec) {
vec[i] <- vec[i] + 1
}
proc.time() - ptm # for-loop
```
---
name: for_loop_counter
# Repeating actions — for loop with a counter
To know the current iteration number on the loop, we can set an external counter:
```{r for.loop.cnt, echo=T}
cnt <- 1
for (i in c(2,4,6,8,10)) {
cat(paste('Iteration', cnt,
'Performing operation on no.', i), '\n')
cnt <- cnt + 1
}
```
---
name: loops_avoid_growing
# Repeating actions — avoid growing data
Avoid changing dimensions of an object inside the loop:
```{r avoid.growing, echo=T}
v <- c() # Initialize
for (i in 1:100) {
v <- c(v, i)
}
cat(head(v), " ... ", tail(v))
```
--
It is much better to do it like this:
```{r avoid.growing3, echo=T}
v <- rep(NA, 100) # Initialize with length
for (i in 1:100) {
v[i] <- i
}
cat(head(v), " ... ", tail(v))
```
--
Always try to know the size of the object you are going to create!
---
name: while_loop
# Repeating actions — the while loop
There is also another type of loop in R, the **while loop** which is executed as long as some condition is true.
```{r loop.while, echo=T}
x <- 1
while (x < 5) {
cat("x equals",x, "\n")
x <- x + 1
}
```
---
name: recursion
exclude: true
# Any questions so far?
<!-- # Recursion
When we explicitely repeat an action using a loop, we talk about **iteration**. We can also repeat actions by means of **recursion**, i.e. when a function calls itself. Let us implement a factorial $!$:
```{r rec.fact, echo=F}
factorial.rec <- function(x) {
if (x == 0 || x == 1)
return(1)
else
return(x * factorial.rec(x - 1)) # Recursive call!
}
factorial.rec(5)
```
# Recursion = iteration?
Yes, every iteration can be converted to recursion (Church-Turing conjecture) and vice-versa. It is not always obvious, but theoretically it is doable. Let's see how to implement *factorial* in iterative manner:
```{r rec.fact.iter, echo=T}
factorial.iter <- function(x) {
if (x == 0 || x == 1)
return(1)
else {
tmp <- 1
for (i in 2:x) {
tmp <- tmp * i
}
return(tmp)
}
}
factorial.iter(5)
```
# Recursion == iteration, really?
More writing for the iterative version, right? What about the time efficiency?
The recursive version:
```{r rec.fact.timing, echo=F}
ptm <- proc.time()
factorial.rec(20)
proc.time() - ptm
```
And the iterative one:
```{r iter.fact.timing, echo=F}
ptm <- proc.time()
factorial.iter(20)
proc.time() - ptm
```
-->
---
name: if_clause
# Decisions, if-clause
Often, one has to take a different course of action depending on a flow of the algorithm.
In R, we use the `if` clause for this purpose.
This is the general syntax:
```
if (condition) {
expr
}
```
--
A simple example:
```{r example if, echo=T}
temp <- -2
if (temp < 0) {
print("It's freezing!")
}
```
---
name: if examples
# Decisions, if-clause
Two more examples of using `if` inside of a loop:
Let's display only the numbers that are greater than 5 in the sequence $[1, 10]$
```{r simple if, echo=T}
v <- 1:10
for (i in v) {
if (i > 5) { # if clause
cat(i, ' ')
}
}
```
--
Let's display only odd numbers in the sequence $[1, 10]$:
```{r if, echo=T}
v <- 1:10
for (i in v) {
if (i %% 2 != 0) { # if clause
cat(i, ' ')
}
}
```
---
name:if_else
# Decisions, if-else
What if we want to perform an action when the first `if` condition is not met?
If we want to print 'o' for an odd number and 'e' for an even, we could write either of:
.pull-left-50[
Only `if` clauses
```{r ifelse1, echo=T}
v <- 1:10
for (i in v) {
if (i %% 2 != 0) { # if clause
cat('o ')
}
if (i %% 2 == 0) { # another if-clause
cat('e ')
}
}
```
]
--
.pull-right-50[
Using `if-else`:
```{r ifelse2, echo=T}
v <- 1:10
for (i in v) {
if (i %% 2 != 0) { # if clause
cat('o ')
} else { # else clause
cat('e ')
}
}
```
]
---
name: elif
exclude: true
# Decisions, if-else-if for more alternatives
So far, so good, but we were only dealing with 2 alternatives.
Let's say that we want to print '?' for zero, 'e' for even and 'o' for an odd number:
We can use the **if-else-if** clause for this!
```{r if.elseif, echo=T}
v <- c(0:10)
for (i in v) {
if (i == 0) { #if clause
cat('? ')
} else if (i %% 2 != 0) { # else-if clause
cat('o ')
} else { # else clause
cat('e ')
}
}
```
---
name: switch
exclude: true
# Switch
If-else clauses operate on logical values. What if we want to take decisions based on non-logical values? Well, if-else will still work by evaluating a number of comparisons, but we can also use **switch**:
```{r switch, echo=T}
switch.demo <- function(x) {
switch(class(x),
logical = cat('logical\n'),
numeric = cat('Numeric\n'),
factor = cat('Factor\n'),
cat('Undefined\n')
)
}
switch.demo(x=TRUE)
switch.demo(x=15)
switch.demo(x=factor('a'))
switch.demo(data.frame())
```
---
name: fns
# Functions
Often, it is really handy to re-use some code we have written or to pack together the code that is doing some task. Functions are a really good way to do this in R:
This is the general syntax
```
function_name <- function(arg1, arg2, ...) {
expr
return(something)
}
```
--
Let's see a simple example of a function to add one to a number:
```{r functions1, echo=T,error=T}
add.one <- function(arg1) {
result <- arg1 + 1
return(result)
}
add.one(1)
```
---
name: fns_defaults
# Functions — arguments with default values
Sometimes, it is good to use default values for some arguments:
```{r functions2, echo=T, error=T}
add.a.num <- function(arg, num=1) {
result <- arg + num
return(result)
}
add.a.num(1) # skip the num argument
```
--
```{r functionresult, echo=T}
add.a.num(1, 5) # overwrite the num argument
add.a.num(1, num=5) # overwrite the num argument
```
--
```{r functionsresult2, echo=T, error=T}
add.a.num(num=1) # skip the first argument
```
---
name:fns_args
# Functions — order of arguments
```{r functions3, echo=T}
args.demo <- function(x, y, arg3) {
print(paste('x =', x, 'y =', y, 'arg3 =', arg3))
}
args.demo(1,2,3)
```
--
```{r functions3b, echo=T}
args.demo(x=1, 2, 3)
```
--
```{r functions3c, echo=T}
args.demo(x=1, y=2, arg3=3)
```
--
```{r functions3d, echo=T}
args.demo(arg3=3, x=1, y=2)
```
---
name: variable_scope
# Functions — variable scope
.pull-left-50[
Functions 'see' not only what has been passed to them as arguments:
```{r fns.varscope, echo=T}
x <- 7
y <- 3
xyplus <- function(x) {
x <- x + y
return(x)
}
xyplus(x)
x
```
]
--
.pull-right-50[
Everything outside the function is called **global environment**. There is a special operator `<<-` for working on global environment:
```{r fns.varscope.glob, echo=T}
x <- 1
xplus <- function(x) {
x <<- x + 1
}
xplus(x)
x
xplus(x)
x
```
]
---
name: fns_ellipsis
# Functions — the `...` argument
There is a special argument **...** (ellipsis) which allows you to give any number of arguments or pass arguments downstream:
```{r fns.3dots, echo=T, fig.height = 3, fig.width = 6}
# Any number of arguments
my.plot <- function(x, y, ...) { # Passing downstream
plot(x, y, las=1, cex.axis=.8, ...)
}
par(mfrow=c(1,2),mar=c(4,4,1,1))
my.plot(1,1)
my.plot(1, 1, col='red', pch=19)
```
- A function enclosing a function is a **wrapper function**
---
name: ellipsis_trick
exclude:true
# Functions — the ellipsis argument trick
What if the authors of, e.g. plot.something wrapper forgot about the `...`?
```{r fns.3dots.trick, echo=T, fig.height = 5, fig.width = 5}
my.plot <- function(x, y) { # Passing downstrem
plot(x, y, las=1, cex.axis=.8, ...)
}
formals(my.plot) <- c(formals(my.plot), alist(... = ))
my.plot(1, 1, col='red', pch=19)
```
---
exclude:true
<!--
name: lazy_eval
# R is lazy!
In R, arguments are evaluated as late as possible, i.e. when they are needed. This is **lazy evaluation**:
```{r lazy.eval, echo=F, eval = T}
h <- function(a = 1, b = d) {
d <- (a + 1) ^ 2
c(a, b)
}
#h()
```
> The above won't be possible in, e.g. C where values of both arguments have to be known before calling a function **eager evaluation**.
-->
---
name: everything_is_a_fn
exclude:true
# In R everything is a function
Because in R everything is a function
```{r fns.everything_1, echo=T}
`+`
```
we can re-define things like this:
```{r fns.everything_2, echo=T}
`+` <- function(e1, e2) { e1 - e2 }
2 + 2
```
and, finally, clean up the mess...
```{r fns.everything_3, echo=T}
rm("+")
2 + 2
```
---
name: infix_fns
exclude:true
# Infix notation
Operators like `+`, `-` or `*` are using the so-called **infix** functions, where the function name is between arguments. We can define our own:
```{r infix, echo=T}
`%p%` <- function(x, y) {
paste(x,y)
}
'a' %p% 'b'
```
---
name:anatomy_of_a_fn
# Anatomy of a function
A function consists of: *formal arguments*, *function body* and *environment*:
```{r fns.formalsbodyenv, echo=T}
formals(add.one)
```
--
```{r fns.formalsbodyenvb, echo=T}
body(add.one)
```
--
```{r fns.formalsbodyenvc, echo=T}
environment(add.one)
environment(sd)
```
---
name: base_fns
# Base functions
When we start R, the following packages are pre-loaded automatically:
```{r preloaded.packages, echo=T}
# .libPaths() # get library location
# library() # see all packages installed
search() # see packages currently loaded
```
Check what basic functions are offered by packages: *base*, *utils* and we will soon work with package *graphics*. If you want to see what statistical functions are in your arsenal, check out package *stats*.
<!-- --------------------- Do not edit this and below --------------------- -->
---
name: end_slide
class: end-slide, middle
count: false
# See you at the next lecture!
```{r, echo=FALSE,child="assets/footer-slide.Rmd"}
```
```{r,include=FALSE,eval=FALSE}
# manually run this to render this document to HTML
#rmarkdown::render("presentation_demo.Rmd")
# manually run this to convert HTML to PDF
#pagedown::chrome_print("presentation_demo.html",output="presentation_demo.pdf")
```