-
Notifications
You must be signed in to change notification settings - Fork 10
/
slide_r_elements_2.Rmd
541 lines (441 loc) · 11.8 KB
/
slide_r_elements_2.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
---
title: "Vectors"
subtitle: "R Foundations for Data Analysis"
author: "Marcin Kierczak, Sebastian DiLorenzo, Guilherme Dias"
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
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"}
```
<!-- ------------ Only edit title, subtitle & author above this ------------ -->
```{r,echo=FALSE,message=FALSE,warning=FALSE}
# load the packages you need
#library(dplyr)
#library(tidyr)
#library(stringr)
#library(ggplot2)
```
---
name: contents
## Contents of the lecture
- variables and their types
- operators
- **vectors**
- **numbers as vectors**
- **strings as vectors**
- matrices
- data frames
- lists
<!-- - objects -->
- repeating actions: iteration and recursion
- decision taking: control structures
- functions in general
- variable scope
- core functions
---
name: cplx_data_str
## Complex data structures
Using the basic data types (`numeric`, `logical` and `character`) one can construct more complex data structures:
<br>
<br>
--
.pull-left-50[
![](images/data_structures.png)
]
.pull-right-50[
dimensions | Homogenous | Heterogenous
----|------------|-----------------
0 | n/a | n/a
1 | vectors | list
2 | matrices | data frame
n | arrays | n/a
]
---
name: atomic_vectors
## Atomic vectors
An *atomic vector*, or simply a *vector*, is a sequence of elements of the same data type.
We build vectors using the function `c()` (combine).
```{r vector, echo=T}
vec <- c(1, 2, 3)
vec
```
In R, even a single number is a one-element vector. Get used to think in terms of vectors...
---
name: atomic_vectors2
## Atomic vectors cted.
You can also create empty/zero vectors of a given type and length:
```{r vec.empty, echo=T}
vector('integer', 5) # a vector of 5 integers
vector('character', 5)
character(5) # does the same
logical(5) # same as vector('logical', 5)
```
---
name: combining_vectors
## Combining two or more vectors
Vectors can easily be combined:
```{r vec.comb, echo=T}
v1 <- c(1,2,3)
v2 <- c('a','b','c')
v3 <- c('do','re','mi')
c(v1, v2, v3)
```
Note that after combining numbers with characters, all elements became character.
This is called a **coercion**.
---
name: basic_vect_arithm
## Basic vector arithmetics
We can perform operations on vectors:
```{r vec.artihmetics, echo=T}
v1 <- c(1, 2, 3, 4)
v2 <- c(7, -9, 15.2, 4)
v1 + v2 # addition
v1 - v2 # subtraction
v1 * v2 # scalar multiplication
v1 / v2 # division
```
---
name: recycling_rule
## Vectors – recycling rule
```{r vec.recycling, echo=T}
v1 <- c(1, 2, 3, 4, 5)
v2 <- c(0, 1)
v1 + v2
```
Values in the shorter vector will be **recycled** (repeated) to match the length of the longer one.
In this case, `v2 <- c(0, 1)` becomes `v2 <- c(0, 1, 0, 1, 0)` so that it can be added to v1.
---
name: vec_indexing
## Vectors – indexing
We can access or retrieve particular elements of a vector by using the [] notation:
```{r vec.indexing, echo=T}
vec <- c('a', 'b', 'c', 'd', 'e')
vec[1] # the first element
vec[5] # the fifth element
vec[-1] # remove the first element
```
---
name: vec_indexing2
## Vectors – indexing cted.
And what happens if we want to retrieve elements outside the vector?
```{r vec.index.beyond, echo=T}
vec <- c('a', 'b', 'c', 'd', 'e')
vec[0] # R counts elements from 1
vec[10] # Positive index past the length of the vector
vec[-6] # Negative index past the length of the vector
```
An index of **zero** will result in an empty vector of the same type as the original vector.
A **positive** index beyond the vector's length will result in an `NA` value.
A **negative** index beyond the vector's length will result in the full unchanged vector. Basically, R ignores your request.
---
name: vec_indexing3
## Vectors – indexing cted.
You can also retrieve elements of a vector using a vector of indices:
```{r vec.index.vec, echo=T}
vec <- c('a', 'b', 'c', 'd', 'e')
vec.ind <- c(1,3,5)
vec[vec.ind]
```
--
Or even a logical vector:
```{r vec.index.vec.log, echo=T}
vec <- c('a', 'b', 'c', 'd', 'e')
vec.ind <- c(TRUE, FALSE, TRUE, FALSE, TRUE)
vec[vec.ind]
```
---
name: vec_indexing_names
## Vectors – indexing using names
You can name elements of your vector:
```{r vec.index.names, echo=T}
vec <- c(23.7, 54.5, 22.7)
names(vec) # by default there are no names
names(vec) <- c('sample1', 'sample2', 'sample3')
vec
vec[c('sample2', 'sample1')]
```
---
name: vec_rem_elem
## Vectors – removing elements
You can return a vector without certain elements:
```{r vec.rm, echo=T}
vec <- c(1, 2, 3, 4, 5)
vec[-5] # without the 5-th element
vec[-(c(1,3,5))] # without elements 1, 3, 5
```
---
name: vec_conditions
## Vectors indexing – conditions
Also logical expressions are allowed in indexing:
```{r vec.index.cond, echo=T}
vec <- c(1, 2, 3, 4, 5)
vec < 3 # we can use the value of this logical comparison
vec[vec < 3]# Et voila!
```
---
name: vec_more_ops
## Vectors – more operations
You can easily reverse a vector:
```{r vec.rev, echo=T}
vec <- c(1, 2, 3, 4, 5)
rev(vec)
```
You can generate vectors of subsequent numbers using `:`, e.g.:
```{r vec.seq.gen, echo=T}
v <- c(5:7)
v
v2 <- c(3:-4)
v2
```
---
name: vec_size
## Vectors – size
To get the size of a vector, use `length()`:
```{r vec.len, echo=T}
vec <- c(1:78)
length(vec)
```
---
name: vec_subst_elem
## Vectors – substitute element
To substitute an element in a vector simply:
```{r vec.subst, echo=T}
vec <- c(1:5)
vec
vec[3] <- 'a' # Note the coercion!
vec
```
--
To insert 'a' at, say, the 2nd position:
```{r vec.ins, echo=T}
c(vec[1], 'a', vec[2:length(vec)])
```
---
name: vec_alter_len
## Vectors – changing the length
What if we write past the vectors last element?
```{r vec.chlen, echo=T}
vec <- c(1:5)
vec
vec[9] <- 9
vec
```
---
name: vec_count_vals
## Vectors – counting values
One may be interested in the count of particular values:
```{r vec.table, echo=T}
vec <- c(1:5, 1:4, 1:3) # a vector with repeating values
table(vec) # table of counts
tab <- table(vec)/length(vec) # table of freqs.
round(tab, digits=3) # and let's round it
```
---
name: vec_sorting
## Vectors – sorting
To sort values of a vector:
```{r vec.sort, echo=T}
vec <- c(1:5, NA, NA, 1:3)
sort(vec) # oops, NAs got lost
sort(vec, na.last = TRUE)
sort(vec, decreasing = TRUE) # in a decreasing order
```
---
name: seq
## Sequences of numbers
R provides also a few handy functions to generate sequences of numbers:
```{r seq, echo=T}
c(1:5, 7:10) # the ':' operator
seq1 <- seq(from=1, to=10, by=2)
seq(from=11, along.with = seq1)
seq(from=10, to=1, by=-2)
```
---
exclude: true
name: printing_brackets
## A detour – printing with `()`
Note what we did here, if you enclose the expression in `()`, the result of assignment will be also printed:
```{r assignprint, echo=T}
seq1 <- seq(from = 1, to = 5)
seq1 # has to be printed explicitly
```
while:
--
```{r assignprint2, echo=T}
(seq2 <- seq(from = 5, to = 1)) # will print automatically
```
---
name: seq2
## Repeating sequences
One may also wish to repeat a value or a vector n times:
```{r rep, echo=T}
rep('a', times=5)
rep(1:5, times=3)
rep(seq(from=1, to=3, by=2), times=2)
```
---
name: random_seq
## Sequences of random numbers
We can use `sample()` to generate sequences of random numbers:
```{r sample, echo=T}
# simulate casting a fair dice 10x
sample(x = c(1:6), size=10, replace = T)
# make it unfair, it is loaded on '3'
myprobs = rep(0.15, times = 6)
myprobs[3] <- 0.25 # a bit higher probability for '3'
sample(x = c(1:6), size = 10, replace = T, prob=myprobs)
```
---
name: simulate_dice
## Fair vs. loaded dice
Now, let us see how this can be useful. We need more than 10 results. Let's cast our dices 10,000 times and plot the freq. distribution.
```{r dices, echo=T}
# simulate casting a fair dice 10x
fair <- sample(x = c(1:6), size=10e3, replace = T)
unfair <- sample(x = c(1:6), size=10e3, replace = T, prob = myprobs)
```
---
name: simulate_dice2
## Fair vs. loaded dice – the result
```{r dices.pic, fig=T, fig.height=4}
t1 <- table(fair)/length(fair)
t2 <- table(unfair)/length(unfair)
plot(0,0,type="n",xlim=c(1,6.0),ylim=c(0,.3),xlab="x",ylab="freq",bty='n', las=1)
grid()
points(1:6, t1, col="olivedrab")
points(1:6, t2, col="slateblue")
legend('topleft', legend = c('fair','unfair'), col = c('olivedrab', 'slateblue'),pch = 15, border = NULL, bty='n')
```
---
name: more_on_sample
## Sample – one more use
The sample function has one more interesting feature, it can be used to randomize order of already created vectors:
```{r sample.shuffle, echo=T}
mychars <- c('a', 'b', 'c', 'd', 'e', 'f')
mychars
sample(mychars)
sample(mychars)
```
---
name: vec_adv
## Vectors/sequences – more advanced operations
```{r vec.adv.oper, echo=T}
v1 <- sample(1:5, size = 4)
v1
max(v1) # max value of the vector
min(v1) # min value
sum(v1) # sum all the elements
```
---
exclude: true
name: vec_adv2
## Vectors/sequences – more advanced operations 2
```{r vec.adv.oper2, echo=T}
v1
diff(v1) # diff. of element pairs
cumsum(v1) # cumulative sum
prod(v1) # product of all elements
```
---
name: vec_adv3
## Vectors/sequences – more advanced operations 3
```{r vec.adv.oper3, echo=T}
v1
cumprod(v1) # cumulative product
cummin(v1) # minimum so far (up to i-th el.)
cummax(v1) # maximum up to i-th element
```
---
exclude: true
name: vec_pairwise_comp
## Vectors/sequences – pairwise comparisons
```{r make.vec2}
v2 <- sample(1:5, size=4)
```
```{r vec.adv.pairwise, echo=T}
v1
v2
v1 <= v2 # direct comparison
pmin(v1, v2) # pairwise min
pmax(v1, v2) # pairwise max
```
---
name: vec_order_rank
## Vectors/sequences – `rank()` and `order()`
rank() and order() are a pair of inverse functions.
```{r vec.adv.rank.order, echo=T}
v1 <- c(1, 3, 4, 5, 3, 2)
rank(v1) # show rank of each value (min has rank 1)
order(v1) # order of indices for a sorted vector
v1[order(v1)]
sort(v1)
```
---
name: factors
## Factors
To work with **nominal** values, R offers a special data type, a *factor*:
```{r factor, echo=T}
vec <- c('blue', 'yellow', 'purple',
'yellow', 'yellow', 'blue')
vec.f <- factor(vec)
summary(vec.f)
```
The levels of a factor are coded alphabetically by default. So blue is coded as 1, purple as 2 and yellow as 3.
Factors are really just a special type of integer vectors.
```{r factor2, echo=T}
as.numeric(vec.f)
```
---
name: factors2
## Factors
You can manually control the coding/mapping of factors and their labels:
```{r factor.coding, echo=T}
vec <- c('blue', 'yellow', 'purple',
'yellow', 'yellow', 'blue')
vec.f <- factor(vec, levels=c('blue', 'purple', 'yellow', 'white'),
labels=c('sea','flower','sun','snow'))
summary(vec.f)
```
---
name: ordered_fac
## Ordered
To work with ordinal scale (ordered) variables, one can also use factors:
```{r ordinal, echo=T}
vec <- c('small', 'tiny', 'large', 'medium')
factor(vec) # rearranged alphabetically
```
--
We can control the order:
```{r ordinal2, echo=T}
factor(vec, levels = c('tiny', 'small', 'medium', 'large'),
ordered=TRUE) # ordered as provided in the levels argument
```
<!-- --------------------- Do not edit this and below --------------------- -->
---
name: end_slide
class: end-slide, middle
count: false
# We will talk about matrices in 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")
```