forked from kzeglinski/new_wehi_r_course
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchapter_1.qmd
More file actions
1754 lines (1215 loc) · 62.4 KB
/
Copy pathchapter_1.qmd
File metadata and controls
1754 lines (1215 loc) · 62.4 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
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
---
filters:
- naquiz
format:
html:
toc: true
toc-location: left
toc-title: "In this chapter:"
---
<!-- things to change: -->
<!-- mention that ~ in path means home -->
<!-- adjust timing -->
# Introduction to R {#sec-chapter01}
In this chapter, we will get familiar with R.
::: {.callout-tip title="Learning Objectives"}
1. Use RStudio to create an R project and R script
2. Perform basic mathematical operations, comparisons and function calls in R
3. Store the results of analysis in variables
4. Describe the different data types and data structures used in R
5. Recall how to use RStudio to find data files and read them in as data frames
:::
## Using RStudio {#sec-usingRstudio}
### What is R and RStudio? {#sec-whatIsR}
**R** is a free and popular statistical programming language, great for performing data analysis. **RStudio** is a free [integrated development environment (IDE)](https://en.wikipedia.org/wiki/Integrated_development_environment) that provides useful support features for writing code. During this course, we will learn how to use RStudio's handy features like projects (which help us to keep track of different analyses) and the environment panel (which shows us all of our data/variables in one place).
### Creating a project {#sec-creatingProject}
Rstudio Projects are a way we can organise our work in RStudio, so that we can resume where we left off and keep different analyses separate. Any time you start working on something new (like this course!) it is recommended that you start a new project. You can see the current project you're working on, switch between projects or create a new project using the menu in the top right hand corner of RStudio:
{width="960"}
To begin this course, let's make a new project. We'll do this in a new directory (folder) so that everything stays organised:
{width="960"}
Next, we need to tell R that we want to make a 'New Project' and not any of the other fancy things we could create:
{width="960"}
Finally, we need to give our project an informative name:
{width="960"}
::: {.callout-note title="Name with underscores, not spaces"}
You'll notice I named my project using an underscore (R_course) rather than a space (R course). **In general, when coding we want to name things without spaces**, so that it is clear to the computer that we are talking about a single entity (the 'R_course') as opposed to multiple things ('R' and 'course'). We'll revisit this idea later in the chapter in @sec-variables
:::
### Creating an R script {#sec-createRScript}
Now that our project is set up, we need to create a file to write our code in:
{width="960"}
This file is called an **R Script**. Don't forget to save your R Script as you work so you don't lose your progress! You can do this through the file menu or by using the keyboard shortcut {{< kbd Cmd-S >}}.
### Overview of the RStudio layout
At this point, your RStudio window should look like this, with four different panels visible:
{width="960"}
This is what they're used for:
1. **The R Script panel.** This is a text document where you can write code, and run it by highlighting the code or putting your cursor on that line, then either clicking the 'Run' button in the top-right corner, or using the {{< kbd Cmd-Enter >}} keyboard shortcut.
2. **The console.** This is where the output (results) of your code will appear. You can also run code in the console, by typing it next to the `>` symbol and pressing {{< kbd Enter >}} but it's better to use the R Script, as the code you write there is saved and acts as a record of your work.
3. **The environment panel.** This is where the data and variables you use in your analysis will be listed. More on this later.
4. **The files/plot/help panel.**
- Under the 'files' tab you can see the files in your current folder
- Under the 'plots' tab you can view the plots you have created
- Under the 'help' tab you can read manual pages to learn how to use functions
Although there are other tabs for some of these panels, they are used for more niche things out of scope of this course. You can read more about it in the [RStudio documentation](https://docs.posit.co/ide/user/ide/guide/ui/ui-panes.html).
### Writing our first piece of code
Now we are ready to write our bit of code! We'll start with one of the most important concepts in programming: comments. Comments are lines of our script that begin with `#` and they are ignored by the computer: they are just notes that we write to ourselves. It's really important to write 'well-commented' code, with plenty of comments that clearly explain what your code is doing, so that your script can easily be understood by whoever looks at it next (whether this is someone else or you revisiting an analysis many months later!)
::: {.callout-warning title="Don't forget your #"}
If you forget the `#` at the start of your comment, R will try to interpret your notes as actual code, and you'll get an error message:
```{r}
#| error: true
oops I forgot the hashtag
```
:::
During this course, we will practice writing well-commented code, but here is an example of how we could write comments to explain the code for one plus one:
```{r}
#| eval: false
# calculate one plus one
1 + 1 # the + symbol means plus
```
Note that comments can be written on their own line or at the end of a line after the code. Crucially, you cannot write any code after a `#` on the same line, as R will ignore it. This is sometimes useful for 'commenting out' code that you don't want to run, but want to keep in your script for later use.
## Practicing R code with maths {#sec-maths}
To practice running R code, let's do some maths. Here's how to code some basic mathematical operations in R:
| Operation | Code | Example |
|----|----|----|
| Addition | `+` | one plus one: `1 + 1` |
| Subtraction | `-` | two minus ten: `2 - 10` |
| Multiplication | `*` | eight times 4: `8 * 4` |
| Division | `/` | ten divided by 3: `10 / 3` |
| Exponents | `^` | three squared: `3 ^ 2` |
| Brackets | `()` | sixteen divided by the result of three minus one: `16 / (3 - 1)` |
Like in regular maths, R follows the order of operations. Here, the `3 + 2` in the brackets will be evaluated first, and then result will be multiplied by 7.
```{r}
# brackets evaluate first
(3 + 2) * 7
```
You might notice when running this code that before the output (result), there is a number one that looks like this: `[1]`. This relates to the length of our output, which here is just one single number (hence the `1`). Later in the chapter we will write code with longer output, and the purpose of this number will become clearer, but you can ignore it for now.
::: {.callout-note title="Using whitespace in code"}
Above we used spaces between the numbers and mathematical operators in our code. R understands code without spaces too, but this makes it easier to read. Note that this is different to when we are naming things, when spaces are bad!
```{r}
# spaces don't matter in code
3 ^ 2
# so both of these should give the same result
3^2
```
:::
::::::::::::::: {.callout-important title="Practice exercises"}
Try these practice questions to test your understanding
:::::::: question
1\. Which R expression would give me a result of 10?
::::::: choices
::: {.choice .correct-choice}
`(2 * 3) + (2 ^ 2)`
:::
::: choice
`(5 - 3) * 4`
:::
::: choice
`1 + 1`
:::
::: choice
`20 - 1`
:::
:::::::
::::::::
:::::::: question
2\. What would be the result of running this line of R code: `# test 1+1`
::::::: choices
::: choice
1
:::
::: choice
2
:::
::: choice
An error
:::
::: {.choice .correct-choice}
Nothing
:::
:::::::
::::::::
<details>
<summary>Solutions</summary>
<p>
1. `(2 * 3) + (2 ^ 2)` is equal to 10. If you're not sure, try copy-pasting this code into the console and running it! The best way to learn is by doing.
2. The code `# test 1+1` is a comment, because it starts with a `#`. This means R ignores it: if you run this code, you won't see any output in the console.
</p>
</details>
:::::::::::::::
## Comparisons {#sec-comparisons}
R can perform comparisons, using the following notation:
| Comparison | Code |
|-------------------------------|--------------|
| Equal to | `==` |
| Not equal to | `!=` |
| Greater/less than | `>` or `<` |
| Greater/less than or equal to | `>=` or `<=` |
::: {.callout-warning title="Mind your equal signs!"}
Be careful to use double equal signs `==` when checking for equality. If you use only one, you'll get an error:
```{r}
#| error: true
1 == 1 # this is TRUE
1 = 1 # this gives an error
```
:::
Comparisons in R return either `TRUE` or `FALSE`:
```{r}
10 > 10
10 >= 10
```
You can also negate the result of a comparison or any TRUE/FALSE value by using the `!` operator before the expression.
```{r}
# gives FALSE (i.e. not TRUE)
!TRUE
# gives TRUE: 1 is not equal to 2, but we've negated the result
!(1 == 2)
```
This is really useful for filtering data, which we will cover in [Chapter @sec-chapter02]
::::::::::::::::::::: {.callout-important title="Practice exercises"}
Try these practice questions to test your understanding
:::::::: question
1\. What would be the result of running this R code: `10 >= 10`
::::::: choices
::: choice
10
:::
::: choice
`FALSE`
:::
::: {.choice .correct-choice}
`TRUE`
:::
::: choice
An error
:::
:::::::
::::::::
:::::::: question
2\. Which of the following R expressions would give me a result of `FALSE`?
::::::: choices
::: choice
`1 == 1`
:::
::: choice
`1 != (3 - 4) * 1`
:::
::: choice
`1 = 10`
:::
::: {.choice .correct-choice}
`1 == 2`
:::
:::::::
::::::::
:::::::: question
3\. What would be the result of running this R code: `!TRUE`
::::::: choices
::: {.choice .correct-choice}
`FALSE`
:::
::: choice
`TRUE`
:::
::: choice
An error
:::
::: choice
Nothing
:::
:::::::
::::::::
<details>
<summary>Solutions</summary>
<p>
1. `10 >= 10` is TRUE because 10 is equal to 10, and we are using the greater than or equal to operator, `>=`.
2. `1 == 2` is the only expression that would give a result of `FALSE`. Be mindful that `1 = 10` is not a valid expression in R, and would give an error (since we need to use the double equal sign `==` for comparisons).
3. `!TRUE` is `FALSE` because we are negating the value using `!`.
</p>
</details>
:::::::::::::::::::::
## Variables {#sec-variables}
### What's a variable?
A variable (also known as an object) in R is like a label we can use to keep track of values. We assign (save) values to variables so that we can refer to them later.
For example, let's say I use R to do some maths:
```{r}
(2 + 6) * 7
```
R outputs simply the result. To use this value later, I would need to assign the output to a variable.
Variables are assigned with the assignment operator `<-` (you can type this using the {{< kbd < >}} and {{< kbd - >}} keys, or use the shortcut {{< kbd alt- >}}).
::: {.callout-note title="Assignment arrows"}
You might be familiar with assigning values to variables using the equal sign `=`, which is used in other programming languages and in maths. Although this does also work in R, **it's preferred to use the arrow** `<-` as this makes it really clear that a variable is being assigned. In this course we'll be using `<-`.
:::
Returning to our example, let's save the result of the above calculation to a variable called `my_number`
```{r}
# assign the result to my_number
my_number <- (2 + 6) * 7
```
Here, R has performed the calculation to the right of the arrow (`(2 + 6) * 7`) and assigned the result of this to the `my_number` variable.
You'll notice that this line of code doesn't produce any output, because it has gone straight into our variable. If we want to know the value of `my_number`, we can either run it as a line of R code, like so:
```{r}
my_number
```
Or, we can look at the environment panel in RStudio:

### Using variables in R code
Variables can be used in place of values (e.g. numbers) in R code. For example, we can use the `my_number` variable in a calculation:
```{r}
# multiply my_number by 2
my_number * 2
```
As the name suggests, variables can vary! We can assign a new value to a variable at any time:
```{r}
# change the value of my_number to 12
my_number <- 12
my_number
```
Because the right hand side of the arrow is evaluated first, you can also assign to a variable a calculation that involves itself:
```{r}
# add 5 to my_number
my_number <- my_number + 5
my_number # value is now 17 since 12 + 5 = 17
```
::: {.callout-warning title="Careful of cases!"}
One thing we need to be careful of when using variables is that R is case-sensitive. This means that `MY_NUMBER` is not the same as `my_number`:
```{r}
#| error: true
# create the my_number variable
my_number <- (2 + 6) * 7
# produces error because MY_NUMBER is not the same as my_number
MY_NUMBER
```
:::
There's not really any harm in keeping variables around, but if you would like to remove them you can use the `rm()` function like so:
```{r}
# assign a variable
my_variable <- 10
# remove it
rm(my_variable) # put the variable name inside the brackets
```
We'll cover functions in more detail in @sec-functions.
If you want to remove ALL the variables you've assigned and start fresh, you can use the broom button in the environment panel:
{width="686"}
Try using the broom to clean up your environment after completing the practice exercises at the end of this section.
### Choosing good variable names
When naming variables, we need to follow these rules:
+----------------------------------------------------------------------+----------------------------------------+
| Rule | Examples |
+======================================================================+========================================+
| **Variable names can only contain letters, numbers and underscores** | ✅ Allowed: `my_number`, `ID_2` |
| | |
| | ❌ Not allowed: `my_number!`, `price$` |
+----------------------------------------------------------------------+----------------------------------------+
| **Variable names can't start with a number** | ✅ Allowed: `my_number_2` |
| | |
| | ❌ Not allowed: `2_my_number` |
+----------------------------------------------------------------------+----------------------------------------+
| **Variable names can't contain spaces** | ✅ Allowed: `my_number` |
| | |
| | ❌ Not allowed: `my number` |
+----------------------------------------------------------------------+----------------------------------------+
If we try to create a variable that breaks these rules, R will give an error:
```{r}
#| error: true
# gives an error because we use a non-allowed character
percentage% <- 100
```
```{r}
#| error: true
# gives an error because we start with a number
1place <- 1
```
```{r}
#| error: true
# gives an error because we have a space
my age <- 5
```
RStudio will try to help you spot these mistakes in your script, by using underlining them in red:

Beyond those three key rules, there are also some best practices we should try to keep in mind when naming our variables:
- Try not to use capital letters. Since R is case sensitive, `Genes` is a different variable to `genes`. It can be easy to forget to use a capital letter, so it's generally better to avoid them if you can.
- Use descriptive names. It's better to use a longer name that describes what the variable is for, rather than a short name that doesn't give much information. For example, `gene_counts` is better than `gc`. You'll thank yourself later when you come back to your code and can't remember what `gc` stands for!
- Avoid using names that are already used in R. For example, `mean` is a function in R that calculates the average of a set of numbers. If you use `mean` as a variable name, this could lead to errors: how will R know if you are referring to the function `mean` or your variable `mean`?
::::::::::::::::::::::::::: {.callout-important title="Practice exercises"}
Try these practice questions to test your understanding
:::::::: question
1\. How would I assign the value of 10 to a variable called `my_variable`?
::::::: choices
::: choice
`10`
:::
::: {.choice .correct-choice}
`my_variable <- 10`
:::
::: choice
`my_variable = 10`
:::
::: choice
`my variable <- 10`
:::
:::::::
::::::::
:::::::: question
2\. I have assigned the value of 10 to a variable called `my_variable` as in Q1. What then would be the output from running this line of R code: `my_variable + 5`?
::::::: choices
::: choice
An error
:::
::: choice
Nothing
:::
::: choice
5
:::
::: {.choice .correct-choice}
15
:::
:::::::
::::::::
:::::::: question
3\. I have assigned the value of 10 to a variable called `my_variable` as in Q1. If I run the code `my_variable <- my_variable + 10`, what is the new value of `my_variable`?
::::::: choices
::: choice
10
:::
::: choice
25
:::
::: {.choice .correct-choice}
20
:::
::: choice
`my_variable`
:::
:::::::
::::::::
:::::::: question
4\. Which of the following is a valid variable name?
::::::: choices
::: choice
`10th_place`
:::
::: choice
`(n)_mice`
:::
::: choice
`disease status`
:::
::: {.choice .correct-choice}
`expression_level`
:::
:::::::
::::::::
<details>
<summary>Solutions</summary>
<p>
1. `my_variable <- 10` is the correct way to assign the value of 10 to a variable called `my_variable`. Remember the arrow `<-` is used for assignment in R.
2. The output would be 15, since `my_variable` is 10 and we are adding 5 to it.
3. The new value of `my_variable` would be 20, since we are adding 10 to the current value of `my_variable` (which is 10). Note that even though we added 5 to `my_variable` earlier, this value is not saved anywhere (since we didn't assign it), so we are starting from the original value of 10.
4. `expression_level` is the only valid variable name. `10th_place` starts with a number, `(n)_mice` contains brackets, and `disease status` contains a space.
</p>
</details>
:::::::::::::::::::::::::::
## Functions {#sec-functions}
### Functions and arguments
Functions are programs that take inputs (also known as arguments) and produce outputs. They have a name, followed by round brackets `()` which contain the arguments.
For example, when we used the code `rm(my_variable)` earlier, the function `rm()` was taking the input (argument) `my_variable` and producing the output of deleting that variable.
Some functions have multiple arguments, which are specified by separating them with commas. Arguments have a set order in which they can be given, or they can be referred to specifically by their name (using a equal sign `=` to provide a value).
As an example, the `round()` function rounds a number to a specified number of decimal places. The first argument is the number to be rounded, and the second argument is the number of decimal places to round to.
```{r}
# we'll use this decimal to demonstrate the round function
decimal <- 3.14159
# round to 3 decimal places
round(decimal, digits = 3)
# we don't have to specify the argument name if we provide the arguments in the correct order
round(decimal, 3)
```
We can see that both of our calls to the `round()` function produced the same result, but the first is easier to understand since we explicitly specified the argument.
Many arguments have default values so you don't need to specify every argument for every function. For example, the `round()` function has a default value of 0 for the `digits` argument, so if you don't specify it, the number will be rounded to the nearest whole number.
```{r}
round(decimal)
```
::: {.callout-warning title="Common errors with functions"}
Here are some common errors you might encounter when using functions. Have a look at the code below and read the error messages to see how the two relate. This will help you to fix typos/errors in your own code.
```{r}
#| error: true
# forgot to enclose the arguments in brackets
round 3.14159
```
```{r}
#| error: true
# forgot the comma between the arguments
round(3.14159 digits = 3)
```
```{r}
#| error: true
# spelt the argument name wrong
round(3.14159, digts = 3)
```
```{r}
#| error: true
# forgot to close the brackets
round(3.14159, digits = 3
```
RStudio will also flag some of these sorts of issues in the script panel, although it won't catch everything:
{width="900"}
:::
### Getting help with functions: within R
When you're using a function, you might not know what arguments it takes, what they do or what their default values are. Nobody can remember all of this information, so one of the most important skills in programming is learning how to access help.
You can access the help pages for a function by typing `?` followed by the name of the function:
```{r}
#| eval: false
?round
```
Or searching for the function in the help tab in RStudio:
{width="688"}
Here's what the help page looks like for the `round` function:
{width="688"}
Help pages can sometimes be quite technical or complicated– for example the help page for `round` also describes various other similar functions for rounding numbers. Often the most important section to look at is the 'arguments' one:
{width="638"}
You can also see help for functions in the script panel, as you are typing your code:
{width="1438"}
It will also suggest you the names of arguments:
{width="1682"}
So, if you get stuck with how to use a function, wait a moment and see if RStudio will suggest what you need.
### Getting help with functions: beyond R
Sometimes, the R help pages can be pretty tricky to understand, and they can't help you if you don't know the name of the function you need! In this course, we'll learn about lots of different functions, but even R experts need to look things up sometimes. Here are some good resources for getting help:
- **Google**. R is a pretty popular language, so if you google 'how to do x in R', you'll probably find an answer
- **Package vignettes**. Many R packages have vignettes, which are short guides to using the package. Once you find the name of a package you might want to use, you should go through their vignettes to see what functions are available and how to use them.
- **ChatGPT** (or similar). AI tools can be really useful in helping you write code, although make sure you double-check the results because it can make mistakes. Tips and advice on how to effectively use AI tools is available in the "Further reading" section.
- **Ask others**! There are lots of R users, and working together is often the best way to solve problems. This could be through online forums, like [StackOverflow](http://stackoverflow.com/questions/tagged/r) or in-person
No matter where you get your help, try to make sure you understand the code you find. Reading the help pages for new functions, or asking an AI like ChatGPT to explain what code is doing is a great way to expand your R knowledge. We also list some recommended additional resources in the "Useful references" section of "Further reading".
::::::::::::::::::::: {.callout-important title="Practice exercises"}
Try these practice questions to test your understanding
:::::::: question
1\. What would be the result of running this R code: `round(3.14159, digits = 2)`
::::::: choices
::: choice
3.14159
:::
::: choice
3.141
:::
::: {.choice .correct-choice}
3.14
:::
::: choice
3
:::
:::::::
::::::::
2\. Look up the help pages for the following functions, and describe what they do:
- `mean()`
- `Sys.Date()`
- `sin()`
:::::::: question
3\. What is wrong with this line of R code: `round(3.14159, digits = 3`
::::::: choices
::: choice
Digits is not a valid argument for the round function
:::
::: choice
You need to use a double equal sign `==` for the digits argument
:::
::: choice
You don't need to specify the digits argument
:::
::: {.choice .correct-choice}
You need to close the brackets at the end of the line
:::
:::::::
::::::::
:::::::: question
4\. Which of the following lines of R code will run without error?
::::::: choices
::: choice
`rm(my_variable`
:::
::: choice
`round(3.14159, Digits = 3)`
:::
::: choice
`round(3.14159 digits = 3)`
:::
::: {.choice .correct-choice}
`round(3.14159, 3)`
:::
:::::::
::::::::
<details>
<summary>Solutions</summary>
<p>
1. The result of running `round(3.14159, digits = 2)` would be 3.14. Remember the `round()` function rounds the number 3.14159 to 2 decimal places, according to the digits argument.
2. The `mean()` function calculates the average of a set of numbers, `Sys.Date()` returns the current date, and `sin()` calculates the sine of an angle (in radians).
3. The line of R code `round(3.14159, digits = 3` is missing a closing bracket at the end, which is why it would produce an error.
4. The line of R code `round(3.14159, 3)` will run without error. The other lines of code have errors: `rm(my_variable` is missing a closing bracket, `round(3.14159, Digits = 3)` has a typo in the argument name (argument names are case sensitive), and `round(3.14159 digits = 3)` is missing a comma between the arguments. Remember that we don't always need to specify the argument names if we provide the arguments in the correct order, which is why we could omit the `digits =` part in the correct line of code.
</p>
</details>
:::::::::::::::::::::
## Data types {#sec-dataTypes}
Every variable in R has a 'type'. The type tells R what kind of data it is and consequently what it can and can't do with the data. For example, it makes sense to perform mathematical functions like multiplication or division on numbers but not on words.
There are three basic types of data in R:
+-------------+---------------------------------------------------------------------------------------------------+-------------------+
| Type | Description | Examples |
+=============+===================================================================================================+===================+
| `logical` | also known as 'boolean', true or false | `TRUE` |
| | | |
| | | `FALSE` |
+-------------+---------------------------------------------------------------------------------------------------+-------------------+
| `numeric` | numbers | `1` |
| | | |
| | | `0.523` |
| | | |
| | | `10000` |
+-------------+---------------------------------------------------------------------------------------------------+-------------------+
| `character` | text/numbers surrounded by quotation marks (double `""` or single `''`). Also known as a 'string' | `'hello'` |
| | | |
| | | `"cat"` |
| | | |
| | | `"my name is..."` |
+-------------+---------------------------------------------------------------------------------------------------+-------------------+
These are called 'atomic' data types as they are the most basic types of data from which other data types derive.
You can find the type of something using the `class()` function:
```{r}
class(TRUE)
class(1)
# whatever you put in quotation marks is always a character
class("hello")
class("TRUE")
class("123")
```
It is important to know the type of your data because, as mentioned earlier, R will not let you perform certain operations on data of the wrong type. For example, you can't add two characters together:
```{r}
#| error: true
# this works
1 + 1
# but this gives an error
"1" + "1"
```
Nor can you use the logical operator `!` on a character:
```{r}
#| error: true
# this works
!TRUE
# but this gives an error
!"TRUE"
```
You'll notice that the error messages for these two examples explain that R can't perform the operation you're asking it to do on that data type.
If you want to change the type of a piece of data, you can use the `as.x()` functions like (e.g.`as.logical()`, `as.numeric()`, and `as.character()`):
```{r}
# convert a number to a character
as.character(100)
# convert a character to a number
as.numeric("100")
```
Of course, it doesn't make sense to make some conversions. In the example below, we can't convert the word "hello" to a number, so we get an `NA`:
```{r}
# if a conversion is not possible, you'll get an NA
as.numeric("hello")
```
::::::::::::::::::::: {.callout-important title="Practice exercises"}
Try these practice questions to test your understanding
:::::::: question
1\. What are the three atomic data types in R?
::::::: choices
::: {.choice .correct-choice}
logical, numeric, character
:::
::: choice
integer, float, string
:::
::: choice
dataset, vector, matrix
:::
::: choice
boolean, text, number
:::
:::::::
::::::::
:::::::: question
2\. How do you find the type of a piece of data in R?
::::::: choices
::: choice
You can't
:::
::: choice
Using the `type()` function
:::
::: choice
Guess
:::
::: {.choice .correct-choice}
Using the `class()` function
:::
:::::::
::::::::
:::::::: question
3\. How would you convert the character "TRUE" to a logical?
::::::: choices
::: choice
`TRUE`
:::
::: {.choice .correct-choice}
`as.logical("TRUE")`
:::
::: choice
You can't convert a character to a logical
:::
::: choice
Using the `logical()` function
:::
:::::::
::::::::
4\. What are the types of the following?
- `11`
- `"eleven"`
- `TRUE`
- `!FALSE`
- `0.49826`
- `"-0.53"`
- `as.numeric("11")`
<details>
<summary>Solutions</summary>
<p>
1. The three atomic data types in R are logical, numeric, and character.
2. You can find the type of a piece of data in R using the `class()` function.
3. To convert the character "TRUE" to a logical, you would use `as.logical("TRUE")` (we always use 'as...' functions to convert between types).
4. The types are:
- `11` is numeric
- `"eleven"` is character
- `TRUE` is logical
- `!FALSE` is logical
- `0.49826` is numeric
- `"-0.53"` is character (even though it looks like a number, it is surrounded by quotation marks so it is a character)
- `as.numeric("11")` is numeric (since we converted the character "11" to a number with the `as.numeric()` function)
</p>
</details>
:::::::::::::::::::::
## Data structures {#sec-datastructures}
Beyond the atomic data types, R has more complex data structures that can store multiple values. These are the building blocks of data analysis in R. The most common data structures are vectors, matrices, and data frames.
This figure summarises their key differences:

### Vectors {#sec-vectors}
A vector is a collection of values **of the same atomic type**. Values in a vector are laid out linearly, one after another.
You can create vectors with the `c()` function, like so: