forked from almaan/genetech
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.Rmd
1183 lines (876 loc) · 35.8 KB
/
main.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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Introduction to R"
author: "FirstName1 LastName1, FirstName2 LastName2, ... " # REPLACE WITH YOUR OWN NAME(S)
date: "`r format(Sys.time(), '%Y-%m-%d')`"
output:
html_document:
toc: true
toc_depth: 4
toc_float:
collapse: false
theme: "readable"
---
<!-- Lab creator: Alma Andersson -->
```{r setup, include=FALSE}
# Document configurations, DO NOT EDIT
knitr::opts_chunk$set(echo = TRUE, eval=FALSE)
options(max.print=200)
```
```{r,echo = FALSE, eval =TRUE}
## Change FALSE to TRUE
## as the last thing you do before
## knitting and hand in in the report
GRADE_MODE <- FALSE
```
Welcome to the first lab! The objective here is to get you _familiar_ with the
programming language `R` and thus prepare you for the more advanced labs. If you
work through these exercises, things will be much easier later on.
With that being said, let's get started!
_NOTE_: Instructions regarding how to hand in this report are found at the very
end of this document.
# Basic R operations
We will first work through some - but far from all - of the most basic elements
of `R`, including:
* Help commands
* Arithmetics
* Logical operators
* Objects
* Data Types
* Arrays (Lists and vectors)
* Array operators
* DataFrames
* DataFrame operators
* Functions (Defining them)
* For loops
* Conditionals
* Plotting
* SummarizedExperiment
## Looking for help
Stack Overflow and Google are your friends, and you should use them vigorously.
![google-so](imgs/google-stack-overflow.png)
However, sometimes you don't have to leave your R session to get the answers you
are looking for. You can get tons of information and examples of usage for most
functions in `R` by typing: `?function_name` or `help(function_name)`, e.g.
`?sum` in your R console.
## Objects and variables
Variables is one of the most basic features of any programming language; in
short you can think of them as placeholders. $pi$ is a great example of a
real-life variable, we use it whenever we want to indicate the value
$3.14159265...$. Similarly, we can assign values or objects a specific name
(e.g, `fancy_variable`), one huge benefit with this is that if we decide to
change the value of `fancy_variable` from `3` to `4`, only the instance where we
define the value of `fancy_variable` will have to be changed rather than all places
where it is used.
In R, you have 2 options when you want to bind an object or value to a name
`var_name <- value` and `var_name = value`. For assignment, the best practice is
to always use `<-`, this is in line with Google's R Style Guide (widely used).
```{r,eval = TRUE, echo=TRUE}
# bind the values 1337 to the variable fancy_name_1
fancy_name_1 <- 1337
# print the variable fancy_name_1
print(sprintf("fancy_name_1 is : %d",fancy_name_1))
```
One variable can be used in the assignment of a value to another variable, as
you may see below:
```{r,echo=TRUE, eval=TRUE}
# bind the sum of fancy_name_1 and 6671 to the variable fancy_name_2
fancy_name_2 <- fancy_name_1 + 6671
# print fancy_name_2
print(sprintf("fancy_name_2 is : %d",fancy_name_2))
```
## Arithmetics
### Arithmetic operations
Computation with and manipulations of numbers are integral parts of any
programming language, hence it's essential to know how to call for these kind of
actions. Below you will see some examples of the more common mathemathical
operations that you will use.
```{r, eval=FALSE}
7 + 4 # => 11 (addition)
7 - 4 # => 3 (subtraction)
7 / 2 # => 3.5 (division)
7 * 2 # => 14 (multiplication)
2 ^ 3 # => 8 (exponents)
7 %% 3 # => 1 (modulo)
```
As in standard mathematics, parentheses are used to indicate the order by which
these operations should be executed. For example:
```{r,eval=TRUE,echo=TRUE}
ex_1 = 7 * 4 / 3 ^ 2
ex_2 = 7 * ( 4 / 3 ) ^ 2
ex_3 = ((7 * 4) / 3) ^ 2
print(sprintf("ex_1 : %f",ex_1))
print(sprintf("ex_2 : %f",ex_2))
print(sprintf("ex_3 : %f",ex_3))
```
### Mathematical operators
There's a plethora of different mathematical functions in 'R', usually their
names resemble those of the mathematical operations they execute, for
example:
```{r, eval=FALSE}
log2(8) # => 3
abs(-9.12) # => 9.12
sqrt(4) # => 2
```
## Logical operators
Once calculations have been performed using different arithmetic operations,
we usually want to assess and _compare_ our results; that's when logical
operators come in handy; when used, they return a value that says either `TRUE` or
`FALSE` depending on the expression you wrote down. Some of the most useful
logical operators are:
* `==` : equal to - `TRUE` if LHS is equal to RHS
* `>` : greater than - `TRUE` if LHS is greater than RHS
* `>=` : greater than or equal to - `TRUE` if LHS is greater than or equal to RHS
* `<` : less than - `TRUE` if LHS is less than RHS
* `<=` : less than or equal to - `TRUE` if LHS is less than or equal to RHS
* `!=` : not equal to - `TRUE` if LHS is not equal to RHS
_COMMENT_: LHS = Left hand side, RHS = Right hand side
For some examples:
```{r,echo = TRUE, eval = FALSE}
3 == 3 # TRUE
2 > 1 # TRUE
9 < 7 # FALSE
4 != 5 #TRUE
5 < 5 #FALSE
5 <= 5 #TRUE
```
Of course we can also compare variables that we have assigned values to:
```{r, eval = TRUE, echo = TRUE}
# Assign values to two variables
foo <- 3.141
bar <- (foo / 2)^3 - 2
# compare their values
foo_greater_than_bar <- foo > bar
# print the value of foo_greater_than_bar
print(foo_greater_than_bar)
# fancy print
print(sprintf("Is foo greater than bar? Answer: %s!",
ifelse(foo_greater_than_bar,"Yes","No")))
```
There are also ways of linking logical expressions, and thus creating a compound
expression. For example, you could check whether two expressions are true at the
_same_ time. The two variants that you mainly will encounter in these labs are:
* `&` - AND : both expressions must be `TRUE`
* `|` - OR : one of the two expressions must be `TRUE`
What do we mean by expressions then? This is best illustrated by some examples:
```{r, echo = TRUE, eval = TRUE}
# set variable values
expr_1 <- 4 < 3
expr_2 <- 9 < 13
# print values of expression 1 and 2
print(paste("The value of expr_1 is :",expr_1))
print(paste("The value of expr_2 is :",expr_2))
# make compound expressions
expr_3 <- expr_1 & expr_2 # is both expr_1 and expr_2 true? (AND operator)
expr_4 <- expr_1 | expr_2 # is either of expr_1 and expr_2 true? (OR operator)
# print values of expression 3 and 4
print(paste("The value of expr_3 is :",expr_3))
print(paste("The value of expr_4 is :",expr_4))
```
**NOTE**: if you want to link expressions rather than variables, it's good practice to use parentheses
```{r, echo = TRUE, eval = TRUE}
expr_1 <- 4 < 2 | 2 < 1 # bad practice
expr_1 <- (4 < 2) | (2 < 1 ) # good practice
```
### Data Classes
Every (programming) language has it's own classes of objects, and you have
already encountered some of them in this lab! Just to get you familiar with the
terminology, some of the _atomic classes_ (that build up every other class in R)
are:
* numerics : real numbers - e.g, `3.0`, `3.14` and `-1000`. More precisely $x \in \mathbb{R}$
* complex : complex numbers - e.g, `1 + 0i`, `-4 + 3i` and `0 + -1i`
* character : characters and strings - e.g., `"a"`, `"hello"` and `"catfish"`
* logicals : boolean values - either `TRUE` or `FALSE`
A lot of errors that arise when coding can be traced back to combining the wrong
classes. For example, if we were to try and add a character to a numeric:
```{r, echo =TRUE, eval = FALSE}
test_1 <- 3 + "a"
```
Would give you the error message `Error in 3 + "a" : non-numeric argument to binary operator`
R, being a _high level_ programming language, implements automatic type coercion
- meaning you don't really have to pay too much attention to making sure you are
using the correct types all the time. For example, if you add a numeric and
complex value, the numeric is converted to a complex type and all is good in the hood:
```{r, echo = TRUE, eval = TRUE}
a_numeric <- 3
a_complex <- 4 - 2i
print(paste("a_numeric + a_complex = ",a_numeric + a_complex))
```
*WARNING* : while the programming becomes easier (e.g., compared to C/C++ or
Java) with this automatic coercion, you should also be cautious - sometimes unexpected
results and errors may be introduced. Take a look at what happens when
you compare a character with a numeric:
```{r, eval = TRUE, echo = FALSE}
result_1 <- "a" > 3
print(paste("a > 3 is : ",result_1))
```
Eh what...? This makes no sense at all, how can we even compare a character with
a number? Shouldn't this, if something, raise an error? It should indeed, but
this is an example of `R` trying to help us a little too much.
What's happening here is that the numeric `3` gets _coerced_ into the character
`"3"` which _can_ be compared to another character (if you, like in R, have
assigned an order to the characters).
## Arrays
The next element to introduce is the _array_, this is another fundamental structures
that you will use *a lot*. In a nutshell, arrays let us associate multiple
values to a single object. We'll be focusing on 1 and 2 dimensional arrays, let
us start with 1d arrays first.
### 1d arrays - lists and vectors
1d arrays come in two flavors, either as _lists_ or as _vectors_. Which you
create accordingly:
```{r,eval=TRUE, echo=TRUE}
a_list <- list(19660206,
"Rick Astley",
"never",
0,
"no",
"you")
a_vector <- c("wind",
"1A",
"earth",
"3B",
"flat",
"water",
"5G",
"round")
```
To access the i:th element of a:
* list - do : `a_list[[i]]` (note the double parenthesis),
* vector - do : `a_vector[i]`
To exemplify, let us access the 4th element from our vector and list respectively:
```{r, echo = TRUE, eval =TRUE}
a_list_4th_element <- a_list[[4]]
a_vector_4th_element <- a_vector[4]
print(paste("The fourth element of our list is : ",a_list_4th_element))
print(paste("The fourth element of our vector is : ",a_vector_4th_element))
```
We could also assign "names" to our array elements (note how we are using `=` and not `<-`):
```{r,eval=TRUE, echo=TRUE}
a_list <- list(birth_date = 19660206,
name = "Rick Astley",
occurance = "never",
problems = 0,
beef = "no",
whom = "you")
a_vector <- c(element_1 = "wind",
slot_1 = "A1",
element_2 = "earth",
slot_2 = "B2",
shape_1 = "flat",
element_3 = "water",
slot_3 = "5G",
shape_2 ="round")
```
We can still access our elements by specifying their position, but also by their
names; sometimes, this allows you to write more **readable code** and makes it
easier to access elements of your arrays.
To access an element by name, for _lists_ use the `$` symbol or `[['name']]`;
for vectors only the second option (`[[name]]`) is valid. To illustrate:
```{r, echo = TRUE, eval = TRUE}
# accessing the elements from our list
print(paste("His name is",
a_list$name,
"and he will",
a_list[["occurance"]],
"give",
a_list[["whom"]],
"up"
)
)
# accessing the elements from our vector
print(paste("We all know that the",
a_vector[["element_2"]],
"is",
a_vector[["shape_1"]],
"and that",
a_vector[["slot_3"]],
"caused COVID"
)
)
```
There's a nice command called `names` that we can use to check the names of our
list and vector elements respectively:
```{r, echo = TRUE, eval = TRUE}
print("The names of our list elements are:")
print(names(a_list)) # here we use the names function to access the names of a_list
print("The names of our vector elements are:")
print(names(a_vector)) # here we use the names function to access the names of a_vector
```
If we want to subset our lists and vectors we could either do:
* `a_list[1:3]` - creates a new list including the first to third element
* `a_list[c(name_1,name_2)]` - creates a new list with elements "name_1" and "name_2"
* `a_vector[1:3]` - creates a new vector including the first to third element
* `a_vector[c(name_1,name_3)]` - creates a new vector with elements "name_1" and "name_3"
As an example:
```{r, echo =TRUE, eval=TRUE}
a_list_subset <- a_list[1:3] #subset a_list
a_vector_subset <- a_vector[c("slot_1","slot_2","slot_3")] #subset a_vector
print('The subsetted list "a_list_subset" is:')
print(a_list_subset)
print('The subsetted vector "a_vector_subset" is:')
print(a_vector_subset)
```
Lists and vectors seem pretty similar, but there is one - very important -
feature that differs between them:
Vectors are *homogeneous* while lists can be *heterogeneous*.
This means that **all elements in a vector must be of the same type**, and if
they aren't they will be coerced to it, i.e., you can not have a vector of both
numerics and characters. See what happens when we try to declare such a vector:
```{r, echo = TRUE, eval = TRUE}
mixed_vector <- c(1, #numeric
"foo", #character
-2, #numeric
"bar" #character
)
# print the type of the first element in "mixed_vector"
print(paste("The type of the first element of mixed_vector is :",
class(mixed_vector[1])))
```
If we use a list instead, the output will be different:
```{r, echo = TRUE, eval = TRUE}
mixed_list <- list(1, #numeric
"foo", #character
-2, #numeric
"bar" #character
)
# print the type of the first element in "mixed_list"
print(paste("The type of the first element of mixed_list is :",
class(mixed_list[[1]])))
```
### Lists of Lists and so forth
The elements of our lists are not restricted to singular values, but could also
be another list or vector. For example:
```{r, echo = TRUE, eval = TRUE}
a_list_of_mixed <- list(list_1 = list("crystals","heals",FALSE),
list_2 = list(6,"days",7,"hours","stuck",TRUE,"Ever Given"),
vector_1 = c("Person", "Woman", "Man", "Camera", "TV")
)
```
*NOTE* : This functionality **does not** exist for vectors. If you try to put
vectors into a vector, they will be "flattened" and just appended to the vector.
If we want to access the second element in the vector that makes up the third
element of `a_list_of_mixed` we would do:
```{r, echo = TRUE, eval = TRUE}
# alternative 1
second_of_third_1 <- a_list_of_mixed[[3]][2]
# alternative 2
second_of_third_2 <- a_list_of_mixed$vector_1[2]
print(paste("(Alt 1) The second element of the third element is :",second_of_third_1))
print(paste("(Alt 2) The second element of the third element is :",second_of_third_2))
```
The object `a_list_of_mixed` to some extent represent a 2d array, we can
traverse both `a_list_of_mixed` itself (first dimension) and then the objects
that constitute its elements (second dimension).
When the lists or vectors that we want to store are of different length, using a
list is the best option, *BUT* if they are of equal length (structured arrays)
there are better options to choose from, being the `matrix` and `dataframe`
types - more on these soon.
### Vector functions
There are many functions that can help us extract useful information from our
vectors, just to expose you to a few:
```{r,echo = TRUE, eval = FALSE}
# define a new vector
a_new_vector <- c(4.1,-2,9.19,18.19,5.21)
#some functions and vector operations
max(a_new_vector) # => max value : 18.19
min(a_new_vector) # => min value : -2
range(a_new_vector) # => min and max value :c(-2, 18.19)
a_new_vector + a_new_vector # => elementwise addition : c(8.20,-4.00,18.38,36.38,10.42)
a_new_vector * a_new_vector # => elementwise multiplication : c(16.8100,4.0000,84.4561,330.8761,27.1441)
a_new_vector %*% a_new_vector # => dot product : 463.2863
4.1 %in% a_new_vector # => check if 4.1 is in vector : TRUE
111 %in% a_new_vector # => check if 111 is in vector : FALSE
```
## Structured 2d Arrays
As eluded to above, when we have structured or _tabular_ data there are two data
structures that are particularly useful:
* Matrices - for homogeneous data
* Data frames - for heterogeneous data
As a reference:
```{r, echo = TRUE, eval = TRUE}
a_matrix <- matrix(data = c(4,1,2,9,-11,-8,1,3,4,21,0,1),
ncol = 4,
nrow = 3
)
a_df <- data.frame(birth_date = c(a_list$birth_date,19691294),
first_name = c(a_list$name,"Jay"),
problems = c(a_list$problems,99),
beef = c(a_list$beef,"yes"),
row.names = c("ind1","ind2")
)
print("this is a matrix")
print(a_matrix)
print("this is a data frame")
print(a_df)
```
Analogously to lists and vectors, we can also extract the names of the the
columns and rows in our 2D arrays, but now we use the functions `colnames` and
`rownames` instead.
```{r, echo = TRUE, eval = TRUE}
# print rownames and colnames of a_matrix
print("The row/colnames of a_matrix are:")
print(rownames(a_matrix))
print(colnames(a_matrix))
# print rownames and colnames of a_df
print("The row/colnames of a_df are:")
print(rownames(a_df))
print(colnames(a_df))
```
As you can see, our matrix does not yet have any row/colnames, to change this we can do:
```{r, echo = TRUE, eval = TRUE}
rownames(a_matrix) <- c("A","B","C")
colnames(a_matrix) <- c("a","b","c","d")
# print rownames and colnames of a_matrix
print("The row/colnames of a_matrix are:")
print(rownames(a_matrix))
print(colnames(a_matrix))
```
To access elements in a matrix we do `a_matrix[row_id,col_id]`, if we want to
access all elements in a specific column then we do `a_matrix[,col_id]` and
similarly for a row `a_matrix[row_id,]`. As an example:
```{r, echo = TRUE, eval = TRUE}
# access the element in the second row and third column in a_matrix
a_matrix[2,3]
# access all elements in the first column
a_matrix[,1]
# access the first and fourth in the second row
a_matrix[2,c(1,4)]
```
The same conventions can be used for data frames to access elements, but you can
also use the `$` operator to access columns in data frames. However, if you do
`a_df[,"col_name"]` or `a_df$col_name` this will return a vector and not a data
frame. To extract a column and preserve its row/colnames do `a_df["col_name"]`.
To exemplify:
```{r, echo = TRUE, eval = TRUE}
# Alt1. extract first columns by [,col_name]
first_col_1 <- a_df[,"birth_date"]
# Alt2. extract first column by $col_name
first_col_2 <- a_df$birth_date
# Alt3. extract first column by [col_name]
first_col_3 <- a_df["birth_date"]
print("(Alt1) : By [,col_name]")
print(first_col_1)
print("(Alt2) By $col_name :")
print(first_col_2)
print("(Alt3) By [col_name] :")
print(first_col_3)
```
### Functions for 2D arrays
We saw how we could apply certain functions to our vectors in order to obtain
for example min and max values, we could do the same for our data frames and matrices.
```{r,echo = TRUE, eval = TRUE}
a_matrix_max <- max(a_matrix)
a_matrix_min <- min(a_matrix)
print(paste("the max value of a_matrix is :", a_matrix_max))
print(paste("the min value of a_matrix is :", a_matrix_min))
```
that is convenient, but what if we wanted the max value in each column and
minimum value in respective row, how do we do this?
One possible solution would be:
```{r,echo=TRUE,eval=TRUE}
a_matrix_col_max <- c(max(a_matrix[,1]),max(a_matrix[,2]),max(a_matrix[,3]),max(a_matrix[,4]))
a_matrix_row_min <- c(min(a_matrix[1,]),min(a_matrix[2,]),min(a_matrix[3,]))
print("max in each column")
print(a_matrix_col_max)
print("min in each row")
print(a_matrix_row_min)
```
Whatever you do, please do not do this. In programming this is what we call a
"shitty ass solution". The main issue here is scaleability, this is not a
feasible approach if you had a 1000x1000 matrix for example. Instead of this
disaster of a solution, we will use a handy function called `apply`.
Let's see how this `apply`function works:
```{r,echo = TRUE, eval = TRUE}
?apply
```
The help section may a bit "icky" to interpret, but in short it says that if we
have an array `X` and a function `FUN` we can apply this function along any
dimension (`MARGIN`) by using apply, it will then treat the rows/columns as
individual vectors to which `FUN` is applied.
**NOTE** : rows are considered the first dimension, columns the second
Let's say that we want to compute the max value of each column (dimension 2) in `a_matrix`, then we have:
* `X` : `a_matrix`
* `MARGIN` : 2
* `FUN` : `max` (note we do not _call_ `max` here, only provide the name)
in action this becomes:
```{r, echo = TRUE, eval = TRUE}
a_matrix_col_max <- apply(a_matrix,2,max)
print(a_matrix_col_max)
```
*COMMENT*: For lists and vectors, similar functions to `apply` exist (check out `lapply` and `sapply`).
Since programmers are inherently lazy, some operations - like getting the column
sums - have been included as standard functions in R, meaning you don't have to
use `apply` but can call them directly. Some examples are:
* `{row,col}Sums`: compute and return the total sum for each row or column
* `{row,col}Means`: compute and return the mean for each row or column
As you can see the results are the same as if we had used `apply`:
```{r, echo = TRUE, eval = TRUE}
a_matrix_row_mean_1 <- apply(a_matrix,1,mean)
a_matrix_row_mean_2 <- rowMeans(a_matrix)
print(paste("Alt1. rowmeans with apply"),a_matrix_row_mean_1)
print(a_matrix_row_mean_1)
print(paste("Alt2. rowmeans with rowMeans"),a_matrix_row_mean_2)
print(a_matrix_row_mean_2)
```
## Functions
Variables allow you to specify a certain value _once_ instead of every time
you use it, functions does the same but for _actions_. In short, you
associate a certain action to a function name, and whenever you want to execute that
action, you simply call the function.
We call the input to our functions "parameters" or "arguments".
You have already used several "pre-defined" functions, like `apply` and `max` -
but sometimes (quite often) we want to expand the repertoire of actions that we
can call for, as well as customizing them for our own needs, that's when we define our
own functions.
The basic structure for a function is as follows:
```{r, eval = TRUE, echo = FALSE}
# DO NOT RUN CHUNK
function_name <- function(parameter_1,parameter_2,...) {
# function body
# this is where the action happens
return(result)
}
```
Say for example that we want a function called `sphere_volume` that computes the
volume of a sphere given its radius, the mathematical formula for this is:
\begin{equation}
V(r) = \frac{4\pi r^3}{3}
\end{equation}
Let us use $3.14$ as an approximation of $\pi$, then our function would look like:
```{r, echo = TRUE, eval = TRUE}
sphere_volume <- function(r) {
pi_approx <- 3.14
volume <- 4.0 / 3.0 * r ^3 * pi_approx
return(volume)
}
```
Let us now test our function
```{r, echo = TRUE, eval = TRUE}
# set radii values
radius_1 <- 9
radius_2 <- 2
# compute volumes
volume_1 <- sphere_volume(radius_1)
volume_2 <- sphere_volume(radius_2)
# print results
msg <- "The volume of a sphere with radius %0.f is %f"
print(sprintf(msg,radius_1,volume_1))
print(sprintf(msg,radius_2,volume_2))
```
## For loops
Just as variables and functions, loops are key features of almost any
programming language. In R we have `while`, `repeat` and `for` loops, but here
we'll focus to the `for` loops.
Briefly summarized, a for loop iterates over some values in a 1d array and, at
each iteration, executes a certain code block. The "skeleton" of a for loop is
as follows:
```{r, echo = TRUE, eval = FALSE}
# DO NOT RUN CHUNK
for (i in vec) {
# loop body
}
```
here `vec` would be the array we iterate over. To give a less abstract example,
we can define a vector that contains all numbers from 1 to 5, done by `vec <-
c(1:5)` and then in each iteration print the value we are at:
```{r, echo = TRUE, eval = TRUE}
vec <- c(1:5)
for (i in vec) {
print(i)
}
```
the elements in our arrays do not have to be numbers or given in a sequential order:
```{r, echo = TRUE, eval = TRUE}
vec <- c("gato","cat","katt","paka")
for (x in vec) {
print(x)
}
```
Of course, for loops are not only used to print stuff, we could for example use
them to generate a Fibonacci series, defined as:
\begin{equation}\
F_n =\Bigg{\{}
\begin{array}{cl}
0 & \textrm{if } n = 1 \\
1 & \textrm{if } n = 2 \\
F_{n-1} + F_{n-2} & \textrm{else} & \\
\end{array}
\end{equation}
_NOTE_: the above equation looks better in the knitted document
Implementing this in could for example look like:
```{r, echo = TRUE, eval = TRUE}
# set desired number of elements in the Fibonacci series
n_elements <- 10
# create a vector F_ to store our elements
# we let F_[1] = 0 since F_1 = 0
# and
# F_[2] = 1 since F_2 = 1
# in the series
F_ <- c(0,1)
# iterate over n=3 to n=10
for (n in c(3:n_elements)) {
# compute the next element in the sequence
x <- F_[n-1] + F_[n-2]
# add element to the F_ vector
F_ <- c(F_,x)
}
# print result
print(sprintf("The first %d numbers of the Fibonacci series are: [%s]",
n_elements,
paste(F_,collapse = ", ")
)
)
```
## Conditionals
Sometimes we want our actions to depend on the output of a function or the value
of a certain variable; as an example from real life, the clothes you put on is
(hopefully) fairly dependent on the temperature outside.
To implement these dependencies we use conditionals, which are : `if`, `else if`
and `else`. The way we structure our conditional statements is as follows:
```{r, echo = TRUE, eval = FALSE}
# DO NOT RUN CHUNK
if (condition_1) {
# code to execute if condition_1 is true
} else if (condition_2) {
# code to execute if condition_1 is FALSE
# and condition_2 is TRUE
} else {
# code to exectue if none of the
# conditions above are TRUE
}
```
**NOTE**: You do not have to include an `else if` or `else` statement, an `if` statement can be used standalone, the reverse is not true.
**NOTE**: You can add as many `else if` statements as you want, but only one `if` and `else`
**NOTE**: You should always follow the order of the statements above: first `if`, then `else if` (if you have any) and last `else`
To give you an example, run the chunk below _a couple of
times_ to see how the conditionals work:
```{r, echo = TRUE, eval = TRUE}
# get a random number between -10 to 25
temperature <- runif(1,-10,25)
# standard text to print
txt <- sprintf("The temperature is %0.f, so",temperature)
# if temperature is below 5 degrees
if (temperature < 5) {
print(paste(txt,"put on a jacket!"))
# if temperature less than 12 degreees (but more than 5)
} else if ( temperature < 12) {
print(paste(txt,"bring a shirt!"))
# if temperature is more than 12 degrees
} else {
print(paste(txt,"it's summertime bby!"))
}
```
## Exercises
Now when we've walked through some of the basics of R, you are more than ready
for some exercises. To pass the lab, all exercises must be correctly completed.
### Exercise 1
Create a data frame (named `count.data`) with 3 samples and 5 genes. Rows are samples, genes are columns. Make all count values = 1
_Hint_: One way is to generate a `matrix` with the value one for all positions and then convert it to a `dataframe`.
```{r,echo = TRUE,eval = TRUE}
#INSERT CODE HERE
```
Make sample 2 have double the amount of counts for _each_ gene. Note that you
should update the existing `count.data` object here not generate a new dataframe.
```{r,echo = TRUE,eval = TRUE}
#INSERT CODE HERE
```
Make sample 3 have the the following counts for each gene (32,16,8,4,2)
```{r,echo = TRUE,eval = TRUE}
#INSERT CODE HERE
```
Cut the count values for gene 2 in half within sample 2 and 3, **and** add 3 counts to gene 4 for sample 1
```{r,echo = TRUE,eval = TRUE}
#INSERT CODE HERE
```
Calculate the mean value of each gene and store this as a vector named `vec`
```{r,echo = TRUE,eval = TRUE}
#INSERT CODE HERE
```
Test run the code below (if no error/warning -> continue with lab)
```{r,echo = TRUE,eval = GRADE_MODE}
source("checks.R")
check_exercise_1(vec)
```
### Exercise 2
In the code chunk below, a vector representing a genomic sequence is
generated, each element in the vector is one base in the sequence. You do
not have to pay attention to this particular code but should **run it**.
```{r, echo = TRUE, eval =TRUE}
sequence <- sample(c("A","C","T","G"),
size = 200,
replace = TRUE
)
sequence <- as.vector(sequence)
print(sprintf("the sequence is : %s",paste0(sequence,collapse = "")))
```
your task is to **write a function** called `base_count` that counts the number of occurrences of each base, i.e., how many A,C,T and G's does `sequence` contain, to be more specific:
`base_count(sequence)` should return a vector where the elements are named
"A,C,T,G" and their associated value represents the number of each base in
`sequence`. This vector could, for example, look like `c(A = 11, C = 132, T =
761, G = 41)`.
```{r, echo = TRUE, eval = GRADE_MODE}
# Possible long solution
base_count <- function(...){
}
```
To test your solution, run the following code chunk:
```{r, echo = TRUE, eval = GRADE_MODE}
source("checks.R")
answer <- base_count(sequence)
check_exercise_2(sequence,answer)
```
### Exercise 3
We usually store data in external files, meaning we usually have to _read_ it
from these files. If we have a comma or tab separated file (extensions `.csv`
and `.tsv`) one way of doing this is by using the `read.table`
function.
If your fields are separated by commas (as in a `.csv`file ) use the argument
`sep=','`, if they are tab separated use the argument `sep = '\t'`.
We will read our data from the file "reads.tsv", it is a **count matrix** with
genes as rows and samples as columns. To read this file the command looks as
follows:
```{r,echo = TRUE, eval = TRUE}
counts <- read.table("reads.tsv", sep = "\t")
```
You could now answer the following questions:
#### Q1
> How many different genes have data been collected from? (help : use `nrow`)
#### Q2
> How many patients have data been collected from? (help : use `dim`)
#### Q3
>Which **5 genes** are most highly expressed across all samples? (help : use `sort` or `order`)
Put your answers into a list `ans_ex3` with the following structure: