forked from datacamp/courses-introduction-to-r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter1.Rmd
551 lines (390 loc) · 15.6 KB
/
chapter1.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
---
title_meta: 'Chapter 1'
title: 'Intro to basics'
description: 'Take your first steps with R. In this chapter, you will learn how to use the console as a calculator and how to assign variables. You will also get to know the basic data types in R. Let''s get started.'
free_preview: true
---
## How it works
```yaml
type: NormalExercise
key: 15d729634a
xp: 100
skills: 1
```
In the editor on the right you should type R code to solve the exercises. When you hit the 'Submit Answer' button, every line of code is interpreted and executed by R and you get a message whether or not your code was correct. The output of your R code is shown in the console in the lower right corner.
R makes use of the `#` sign to add comments, so that you and others can understand what the R code is about. Just like Twitter! Comments are not run as R code, so they will not influence your result. For example, _Calculate 3 + 4_ in the editor on the right is a comment.
You can also execute R commands straight in the console. This is a good way to experiment with R code, as your submission is not checked for correctness.
`@instructions`
- In the editor on the right there is already some sample code. Can you see which lines are actual R code and which are comments?
- Add a line of code that calculates the sum of 6 and 12, and hit the 'Submit Answer' button.
`@hint`
Just add a line of R code that calculates the sum of 6 and 12, just like the example in the sample code!
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Calculate 3 + 4
3 + 4
# Calculate 6 + 12
```
`@solution`
```{r}
# Calculate 3 + 4
3 + 4
# Calculate 6 + 12
6 + 12
```
`@sct`
```{r}
ex() %>% check_output_expr("18", missing_msg = "Make sure to add `6 + 12` on a new line. Do not start the line with a `#`, otherwise your R code is not executed!")
success_msg("Awesome! See how the console shows the result of the R code you submitted? Now that you're familiar with the interface, let's get down to R business!")
```
---
## Arithmetic with R
```yaml
type: NormalExercise
key: 720745eda5
xp: 100
skills: 1
```
In its most basic form, R can be used as a simple calculator. Consider the following arithmetic operators:
- Addition: `+`
- Subtraction: `-`
- Multiplication: `*`
- Division: `/`
- Exponentiation: `^`
- Modulo: `%%`
The last two might need some explaining:
- The `^` operator raises the number to its left to the power of the number to its right: for example `3^2` is 9.
- The modulo returns the remainder of the division of the number to the left by the number on its right, for example 5 modulo 3 or `5 %% 3` is 2.
With this knowledge, follow the instructions to complete the exercise.
`@instructions`
- Type `2^5` in the editor to calculate 2 to the power 5.
- Type `28 %% 6` to calculate 28 modulo 6.
- Submit the answer and have a look at the R output in the console.
- Note how the `#` symbol is used to add comments on the R code.
`@hint`
Another example of the modulo operator: `9 %% 2` equals `1`.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# An addition
5 + 5
# A subtraction
5 - 5
# A multiplication
3 * 5
# A division
(5 + 5) / 2
# Exponentiation
# Modulo
```
`@solution`
```{r}
# An addition
5 + 5
# A subtraction
5 - 5
# A multiplication
3 * 5
# A division
(5 + 5) / 2
# Exponentiation
2 ^ 5
# Modulo
28 %% 6
```
`@sct`
```{r}
msg = "Do not remove the other arithmetic examples!"
ex() %>% check_output_expr("2^5", missing_msg = "The exponentiation example is not correct. Write `2 ^ 5` on a new line.")
ex() %>% check_output_expr("28 %% 6", missing_msg = "There seems to be an issue with the modulo example. Write `28 %% 6` on a new line.")
success_msg("Great! Head over to the next exercise.")
```
---
## Variable assignment
```yaml
type: NormalExercise
key: 5f200ffd43
xp: 100
skills: 1
```
A basic concept in (statistical) programming is called a **variable**.
A variable allows you to store a value (e.g. 4) or an object (e.g. a function description) in R. You can then later use this variable's name to easily access the value or the object that is stored within this variable.
You can assign a value 4 to a variable `my_var` with the command
```
my_var <- 4
```
`@instructions`
Over to you: complete the code in the editor such that it assigns the value 42 to the variable `x` in the editor. Submit the answer. Notice that when you ask R to print `x`, the value 42 appears.
`@hint`
Look at how the value 4 was assigned to `my_variable` in the exercise's assignment. Do the exact same thing in the editor, but now assign 42 to the variable `x`.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Assign the value 42 to x
x <-
# Print out the value of the variable x
x
```
`@solution`
```{r}
# Assign the value 42 to x
x <- 42
# Print out the value of the variable x
x
```
`@sct`
```{r}
ex() %>% check_object("x", undefined_msg = "Make sure to define a variable `x`.") %>% check_equal(incorrect_msg = "Make sure that you assign the correct value to `x`.")
success_msg("Good job! Have you noticed that R does not print the value of a variable to the console when you did the assignment? `x <- 42` did not generate any output, because R assumes that you will be needing this variable in the future. Otherwise you wouldn't have stored the value in a variable in the first place, right? Proceed to the next exercise!")
```
---
## Variable assignment (2)
```yaml
type: NormalExercise
key: c5944b90eb
xp: 100
skills: 1
```
Suppose you have a fruit basket with five apples. As a data analyst in training, you want to store the number of apples in a variable with the name `my_apples`.
`@instructions`
- Type the following code in the editor: `my_apples <- 5`. This will assign the value 5 to `my_apples`.
- Type: `my_apples` below the second comment. This will print out the value of `my_apples`.
- Submit your answer, and look at the output: you see that the number 5 is printed. So R now links the variable `my_apples` to the value 5.
`@hint`
Remember that if you want to assign a number or an object to a variable in R, you can make use of the assignment operator `<-`. Alternatively, you can use `=`, but `<-` is widely preferred in the R community.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Assign the value 5 to the variable my_apples
# Print out the value of the variable my_apples
```
`@solution`
```{r}
# Assign the value 5 to the variable my_apples
my_apples <- 5
# Print out the value of the variable my_apples
my_apples
```
`@sct`
```{r}
ex() %>% check_object("my_apples", undefined_msg = "Please make sure to define a variable `my_apples`.") %>% check_equal(incorrect_msg = "Make sure that you assign the correct value to `my_apples`.")
ex() %>% check_output_expr("my_apples", missing_msg = "Have you explicitly told R to print out the `my_apples` variable to the console?")
success_msg("Great! Continue to the next exercise!")
```
---
## Variable assignment (3)
```yaml
type: NormalExercise
key: 1c1bd25045
xp: 100
skills: 1
```
Every tasty fruit basket needs oranges, so you decide to add six oranges. As a data analyst, your reflex is to immediately create the variable `my_oranges` and assign the value 6 to it. Next, you want to calculate how many pieces of fruit you have in total. Since you have given meaningful names to these values, you can now code this in a clear way:
```
my_apples + my_oranges
```
`@instructions`
- Assign to `my_oranges` the value 6.
- Add the variables `my_apples` and `my_oranges` and have R simply print the result.
- Assign the result of adding `my_apples` and `my_oranges` to a new variable `my_fruit`.
`@hint`
`my_fruit` is just the sum of `my_apples` and `my_oranges`. You can use the `+` operator to sum the two and `<-` to assign that value to the variable `my_fruit`.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Assign a value to the variables my_apples and my_oranges
my_apples <- 5
# Add these two variables together
# Create the variable my_fruit
```
`@solution`
```{r}
# Assign a value to the variables my_apples and my_oranges
my_apples <- 5
my_oranges <- 6
# Add these two variables together
my_apples + my_oranges
# Create the variable my_fruit
my_fruit <- my_apples + my_oranges
```
`@sct`
```{r}
msg <- "Have you used `my_fruit <- my_apples + my_oranges` to create the `my_fruit` variable?"
ex() %>% check_object("my_apples") %>% check_equal(incorrect_msg = "Keep the line that assigns 5 to `my_apples`.")
ex() %>% check_object("my_oranges") %>% check_equal(incorrect_msg = "Keep the line that assigns 6 to `my_oranges`.")
ex() %>% check_output_expr("my_apples + my_oranges",missing_msg = "Make sure to print out the result of adding `my_apples` and `my_oranges`. The code example in the description already gives away the answer to this instruction!")
ex() %>% check_object("my_fruit", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
success_msg("Nice one! The great advantage of doing calculations with variables is reusability. If you just change `my_apples` to equal 12 instead of 5 and rerun the script, `my_fruit` will automatically update as well. Continue to the next exercise.")
```
---
## Apples and oranges
```yaml
type: NormalExercise
key: 915fcc7c99
xp: 100
skills: 1
```
Common knowledge tells you not to add apples and oranges. But hey, that is what you just did, no :-)? The `my_apples` and `my_oranges` variables both contained a number in the previous exercise. The `+` operator works with numeric variables in R. If you really tried to add "apples" and "oranges", and assigned a text value to the variable `my_oranges` (see the editor), you would be trying to assign the addition of a numeric and a character variable to the variable `my_fruit`. This is not possible.
`@instructions`
- Submit the answer and read the error message. Make sure to understand why this did not work.
- Adjust the code so that R knows you have 6 oranges and thus a fruit basket with 11 pieces of fruit.
`@hint`
You have to assign the numeric value `6` to the `my_oranges` variable instead of the character value `"six"`. Note how the quotation marks are used to indicate that `"six"` is a character.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Assign a value to the variable my_apples
my_apples <- 5
# Fix the assignment of my_oranges
my_oranges <- "six"
# Create the variable my_fruit and print it out
my_fruit <- my_apples + my_oranges
my_fruit
```
`@solution`
```{r}
# Assign a value to the variable my_apples
my_apples <- 5
# Fix the assignment of my_oranges
my_oranges <- 6
# Create the variable my_fruit and print it out
my_fruit <- my_apples + my_oranges
my_fruit
```
`@sct`
```{r}
ex() %>% check_error(incorrect_msg = "You can do this by setting the `my_oranges` variable to a numeric value, not a string!")
ex() %>% check_object("my_apples") %>% check_equal(incorrect_msg = "Make sure that `my_apples` still contains `5`.")
ex() %>% check_object("my_oranges") %>% check_equal(incorrect_msg = "Make sure that `my_oranges` is equal to `6`.")
ex() %>% check_object("my_fruit") %>% check_equal(incorrect_msg = "The value of `my_fruit` is not correct. It should be 11, the sum of `my_apples` and `my_oranges`.")
ex() %>% check_object("my_fruit")%>% check_or(
check_code(.,"my_fruit\\s*<-\\s*my_apples\\s*\\+\\s*my_oranges", missing_msg = "Did you create `my_fruit` as the sum of variables `my_apples` and `my_oranges`?", append=F),
check_code(.,"my_fruit\\s*<-\\s*my_oranges\\s*\\+\\s*my_apples", missing_msg = "Did you create `my_fruit` as the sum of variables `my_apples` and `my_oranges`?", append=F)
)
ex() %>% check_output_expr("my_fruit", missing_msg = "Don't remove the line that prints out `my_fruit`.")
success_msg("Awesome, keep up the good work! Continue to the next exercise.")
```
---
## Basic data types in R
```yaml
type: NormalExercise
key: 0f23107394
xp: 100
skills: 1
```
R works with numerous data types. Some of the most basic types to get started are:
- Decimal values like `4.5` are called **numerics**.
- Whole numbers like `4` are called **integers**. Integers are also numerics.
- Boolean values (`TRUE` or `FALSE`) are called **logical**.
- Text (or string) values are called **characters**.
Note how the quotation marks in the editor indicate that `"some text"` is a string.
`@instructions`
Change the value of the:
- `my_numeric` variable to `42`.
- `my_character` variable to `"universe"`. Note that the quotation marks indicate that `"universe"` is a character.
- `my_logical` variable to `FALSE`.
Note that R is case sensitive!
`@hint`
Replace the values in the editor with the values that are provided in the exercise. For example:
`my_numeric <- 42` assigns the value 42 to the variable `my_numeric`.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Change my_numeric to be 42
my_numeric <- 42.5
# Change my_character to be "universe"
my_character <- "some text"
# Change my_logical to be FALSE
my_logical <- TRUE
```
`@solution`
```{r}
# Change my_numeric to be 42
my_numeric <- 42
# Change my_character to be "universe"
my_character <- "universe"
# Change my_logical to be FALSE
my_logical <- FALSE
```
`@sct`
```{r}
ex() %>% check_object("my_numeric") %>% check_equal(incorrect_msg = "Have you correctly changed the declaration of `my_numeric` so it contains the value 42?")
ex() %>% check_object("my_character") %>% check_equal(incorrect_msg = "Have you correctly changed `my_character` to `\"universe\"`? Don't forget the quotes!")
ex() %>% check_object("my_logical") %>% check_equal(incorrect_msg = "Have you correctly changed `my_logical` to `FALSE`? All letters of `FALSE` should be capitalized!")
success_msg("Great work! Continue to the next exercise.")
```
---
## What's that data type?
```yaml
type: NormalExercise
key: 99b549229d
xp: 100
skills: 1
```
Do you remember that when you added `5 + "six"`, you got an error due to a mismatch in data types? You can avoid such embarrassing situations by checking the data type of a variable beforehand. You can do this with the `class()` function, as the code in the editor shows.
`@instructions`
Complete the code in the editor and also print out the classes of `my_character` and `my_logical`.
`@hint`
The code that prints the data type of `my_numeric` is already included; do a similar things for `my_character` and `my_logical`.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Declare variables of different types
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE
# Check class of my_numeric
class(my_numeric)
# Check class of my_character
# Check class of my_logical
```
`@solution`
```{r}
# Declare variables of different types:
my_numeric <- 42
my_character <- "universe"
my_logical <- FALSE
# Check class of my_numeric
class(my_numeric)
# Check class of my_character
class(my_character)
# Check class of my_logical
class(my_logical)
```
`@sct`
```{r}
msg <- "Do not change the declaration of the variables!"
ex() %>% check_object("my_numeric", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("my_character", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("my_logical", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
patt <- "Have you included `class(%1$s)` to print out the data type of `%1$s`?"
ex() %>% check_output_expr("class(my_numeric)",missing_msg = "Do not remove the code that prints out the type of `my_numeric`.")
ex() %>% check_output_expr("class(my_character)",missing_msg = sprintf(patt, "my_character"))
ex() %>% check_output_expr("class(my_logical)",missing_msg = sprintf(patt, "my_logical"))
success_msg("Congratulations! This was the last exercise for this chapter. Head over to the next chapter to get immersed in the world of vectors!")
```