forked from datacamp/courses-introduction-to-r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter5.Rmd
763 lines (551 loc) · 25.9 KB
/
chapter5.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
---
title_meta: Chapter 5
title: Data frames
description: >-
Most datasets you will be working with will be stored as data frames. By the
end of this chapter, you will be able to create a data frame, select
interesting parts of a data frame, and order a data frame according to certain
variables.
---
## What's a data frame?
```yaml
type: NormalExercise
key: 7f95849020a2563168920409022ce7bed20835b5
xp: 100
skills:
- 1
```
You may remember from the chapter about matrices that all the elements that you put in a matrix should be of the same type. Back then, your data set on Star Wars only contained numeric elements.
When doing a market research survey, however, you often have questions such as:
- 'Are you married?' or 'yes/no' questions (`logical`)
- 'How old are you?' (`numeric`)
- 'What is your opinion on this product?' or other 'open-ended' questions (`character`)
- ...
The output, namely the respondents' answers to the questions formulated above, is a data set of different data types. You will often find yourself working with data sets that contain different data types instead of only one.
A data frame has the variables of a data set as columns and the observations as rows. This will be a familiar concept for those coming from different statistical software packages such as SAS or SPSS.
`@instructions`
Submit the answer. The data from the built-in example data frame [`mtcars`](http://www.rdocumentation.org/packages/datasets/functions/mtcars) will be printed to the console.
`@hint`
Just submit the answer and witness the magic!
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Print out built-in R data frame
mtcars
```
`@solution`
```{r}
# Print out built-in R data frame
mtcars
```
`@sct`
```{r}
ex() %>% check_output_expr("mtcars", missing_msg = "Do not change anything about the code, Make sure that you output `mtcars`.")
success_msg("Great! Continue to the next exercise.")
```
---
## Quick, have a look at your data set
```yaml
type: NormalExercise
key: 3d0e64ecf5f69521ee538ecc713caa02b8b0ec46
xp: 100
skills:
- 1
```
Wow, that is a lot of cars!
Working with large data sets is not uncommon in data analysis. When you work with (extremely) large data sets and data frames, your first task as a data analyst is to develop a clear understanding of its structure and main elements. Therefore, it is often useful to show only a small part of the entire data set.
So how to do this in R? Well, the function [`head()`](http://www.rdocumentation.org/packages/utils/functions/head) enables you to show the first observations of a data frame. Similarly, the function [`tail()`](http://www.rdocumentation.org/packages/utils/functions/head) prints out the last observations in your data set.
Both [`head()`](http://www.rdocumentation.org/packages/utils/functions/head) and [`tail()`](http://www.rdocumentation.org/packages/utils/functions/head) print a top line called the 'header', which contains the names of the different variables in your data set.
`@instructions`
Call [`head()`](http://www.rdocumentation.org/packages/utils/functions/head) on the [`mtcars`](http://www.rdocumentation.org/packages/datasets/functions/mtcars) data set to have a look at the header and the first observations.
`@hint`
`head(mtcars)` will show the first observations of the `mtcars` data frame.
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Call head() on mtcars
```
`@solution`
```{r}
# Call head() on mtcars
head(mtcars)
```
`@sct`
```{r}
ex() %>% check_function("head") %>% check_arg('x') %>% check_equal(incorrect_msg = "Have you correctly passed `mtcars` to the `head()` function?")
ex() %>% check_output_expr("head(mtcars)", missing_msg = "Simply print out the result of the `head()` call, no need to assign it to a new variable.")
success_msg("Wonderful! So, what do we have in this data set? For example, `hp` represents the car's horsepower; the Datsun has the lowest horse power of the 6 cars that are displayed. For a full overview of the variables' meaning, type `?mtcars` in the console and read the help page. Continue to the next exercise!");
```
---
## Have a look at the structure
```yaml
type: NormalExercise
key: f4d5b1a2c4aef31645fc7e3505e699fb6e48f3e6
xp: 100
skills:
- 1
```
Another method that is often used to get a rapid overview of your data is the function [`str()`](http://www.rdocumentation.org/packages/utils/functions/str). The function [`str()`](http://www.rdocumentation.org/packages/utils/functions/str) shows you the structure of your data set. For a data frame it tells you:
- The total number of observations (e.g. 32 car types)
- The total number of variables (e.g. 11 car features)
- A full list of the variables names (e.g. `mpg`, `cyl` ... )
- The data type of each variable (e.g. `num`)
- The first observations
Applying the [`str()`](http://www.rdocumentation.org/packages/utils/functions/str) function will often be the first thing that you do when receiving a new data set or data frame. It is a great way to get more insight in your data set before diving into the real analysis.
`@instructions`
Investigate the structure of [`mtcars`](http://www.rdocumentation.org/packages/datasets/functions/mtcars). Make sure that you see the same numbers, variables and data types as mentioned above.
`@hint`
Use the [`str()`](http://www.rdocumentation.org/packages/utils/functions/str) function on [`mtcars`](http://www.rdocumentation.org/packages/datasets/functions/mtcars).
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Investigate the structure of mtcars
```
`@solution`
```{r}
# Investigate the structure of mtcars
str(mtcars)
```
`@sct`
```{r}
ex() %>% check_output_expr("str(mtcars)", missing_msg = "Have you correctly called `str()` on `mtcars`?")
success_msg("Nice work! Can you find all the information that is listed in the exercise's assignment? Continue to the next exercise.")
```
---
## Creating a data frame
```yaml
type: NormalExercise
key: df0b89706d90526b3c0bbe15e400b74cbd900704
xp: 100
skills:
- 1
```
Since using built-in data sets is not even half the fun of creating your own data sets, the rest of this chapter is based on your personally developed data set. Put your jet pack on because it is time for some space exploration!
As a first goal, you want to construct a data frame that describes the main characteristics of eight planets in our solar system. According to your good friend Buzz, the main features of a planet are:
- The type of planet (Terrestrial or Gas Giant).
- The planet's diameter relative to the diameter of the Earth.
- The planet's rotation across the sun relative to that of the Earth.
- If the planet has rings or not (TRUE or FALSE).
After doing some high-quality research on [Wikipedia](http://en.wikipedia.org/wiki/Planet), you feel confident enough to create the necessary vectors: `name`, `type`, `diameter`, `rotation` and `rings`; these vectors have already been coded up in the editor. The first element in each of these vectors correspond to the first observation.
You construct a data frame with the [`data.frame()`](http://www.rdocumentation.org/packages/base/functions/data.frame) function. As arguments, you pass the vectors from before: they will become the different columns of your data frame. Because every column has the same length, the vectors you pass should also have the same length. But don't forget that it is possible (and likely) that they contain different types of data.
`@instructions`
Use the function [`data.frame()`](http://www.rdocumentation.org/packages/base/functions/data.frame) to construct a data frame. Pass the vectors `name`, `type`, `diameter`, `rotation` and `rings` as arguments to `data.frame()`, in this order. Call the resulting data frame `planets_df`.
`@hint`
Your `data.frame()` call starts as follows:
```
data.frame(planets, type, diameter)
```
Can you finish it?
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Definition of vectors
name <- c("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune")
type <- c("Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet", "Gas giant",
"Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532,
11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03,
0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
# Create a data frame from the vectors
planets_df <-
```
`@solution`
```{r}
# Definition of vectors
name <- c("Mercury", "Venus", "Earth",
"Mars", "Jupiter", "Saturn",
"Uranus", "Neptune")
type <- c("Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet",
"Terrestrial planet", "Gas giant",
"Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532,
11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03,
0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
# Create a data frame from the vectors
planets_df <- data.frame(name, type, diameter, rotation, rings)
```
`@sct`
```{r}
msg = "Do not change anything about the definition of the vectors. Only add a `data.frame()` call to create `planets_df`."
ex() %>% check_object("name", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("type", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("diameter", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("rotation", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("rings", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("planets_df") %>% check_equal(incorrect_msg = "Have you correctly called `data.frame()` to create `planets_df`. Inside `data.frame()`, make sure to pass all vectors in the correct order: `name`, `type`, `diameter`, `rotation` and finally `rings`.")
success_msg("Great job! Continue to the next exercise. The logical next step, as you know by now, is inspecting the data frame you just created. Head over to the next exercise.");
```
---
## Creating a data frame (2)
```yaml
type: NormalExercise
key: c13ea421dd078030a225f49e53a8927ce8fefbe0
xp: 100
skills:
- 1
```
The `planets_df` data frame should have 8 observations and 5 variables. It has been made available in the workspace, so you can directly use it.
`@instructions`
Use [`str()`](http://www.rdocumentation.org/packages/utils/functions/str) to investigate the structure of the new `planets_df` variable.
`@hint`
`planets_df` is already available in your workspace, so `str(planets_df)` will do the trick.
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# Check the structure of planets_df
```
`@solution`
```{r}
# Check the structure of planets_df
str(planets_df)
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame that is already available in the workspace!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_output_expr("str(planets_df)", missing_msg = "Have you correctly displayed the structure of `planets_df`? Use `str()` to do this!")
success_msg("Awesome! Now that you have a clear understanding of the `planets_df` data set, it's time to see how you can select elements from it. Learn all about in the next exercises!")
```
---
## Selection of data frame elements
```yaml
type: NormalExercise
key: 8c664726b8a173cda730cbb20a52ac1795d9a0e9
xp: 100
skills:
- 1
```
Similar to vectors and matrices, you select elements from a data frame with the help of square brackets `[ ]`. By using a comma, you can indicate what to select from the rows and the columns respectively. For example:
- `my_df[1,2]` selects the value at the first row and second column in `my_df`.
- `my_df[1:3,2:4]` selects rows 1, 2, 3 and columns 2, 3, 4 in `my_df`.
Sometimes you want to select all elements of a row or column. For example, `my_df[1, ]` selects all elements of the first row. Let us now apply this technique on `planets_df`!
`@instructions`
- From `planets_df`, select the diameter of Mercury: this is the value at the first row and the third column. Simply print out the result.
- From `planets_df`, select all data on Mars (the fourth row). Simply print out the result.
`@hint`
To select the diameter for Venus (the second row), you would need: `planets_df[2,3]`. What do you need for Mercury then?
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# The planets_df data frame from the previous exercise is pre-loaded
# Print out diameter of Mercury (row 1, column 3)
# Print out data for Mars (entire fourth row)
```
`@solution`
```{r}
# The planets_df data frame from the previous exercise is pre-loaded
# Print out diameter of Mercury (row 1, column 3)
planets_df[1,3]
# Print out data for Mars (entire fourth row)
planets_df[4, ]
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_output_expr("planets_df[1,3]", missing_msg = "Have you correctly selected and printed out the diameter for Mercury? You can use `[1,3]`.")
ex() %>% check_output_expr("planets_df[4, ]", missing_msg = "Have you correctly selected and printed out all data for Mars? You can use `[4,]`.")
success_msg("Great! Apart from selecting elements from your data frame by index, you can also use the column names. To learn how, head over to the next exercise.")
```
---
## Selection of data frame elements (2)
```yaml
type: NormalExercise
key: faf104fb0c605fd89f048648a4a588200bc89c76
xp: 100
skills:
- 1
```
Instead of using numerics to select elements of a data frame, you can also use the variable names to select columns of a data frame.
Suppose you want to select the first three elements of the `type` column. One way to do this is
```
planets_df[1:3,2]
```
A possible disadvantage of this approach is that you have to know (or look up) the column number of `type`, which gets hard if you have a lot of variables. It is often easier to just make use of the variable name:
```
planets_df[1:3,"type"]
```
`@instructions`
Select and print out the first 5 values in the `"diameter"` column of `planets_df`.
`@hint`
You can select the first five values with `planets_df[1:5, ...]`. Can you fill in the `...` bit to only select the `"diameter"` column?
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# The planets_df data frame from the previous exercise is pre-loaded
# Select first 5 values of diameter column
```
`@solution`
```{r}
# The planets_df data frame from the previous exercise is pre-loaded
# Select first 5 values of diameter column
planets_df[1:5, "diameter"]
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_output_expr("planets_df[1:5, \"diameter\"]", missing_msg = "Have you correctly selected the first five values from the diameter column and printed them out? You can use `[1:5, \"diameter\"]` here.")
success_msg("Nice! Continue to the next exercise!")
```
---
## Only planets with rings
```yaml
type: NormalExercise
key: e550ecb6ec45b856e6160ddfbb3d7875998e8365
xp: 100
skills:
- 1
```
You will often want to select an entire column, namely one specific variable from a data frame. If you want to select all elements of the variable `diameter`, for example, both of these will do the trick:
```
planets_df[,3]
planets_df[,"diameter"]
```
However, there is a short-cut. If your columns have names, you can use the `$` sign:
```
planets_df$diameter
```
`@instructions`
- Use the `$` sign to select the `rings` variable from `planets_df`. Store the vector that results as `rings_vector`.
- Print out `rings_vector` to see if you got it right.
`@hint`
`planets_df$diameter` selects the `diameter` column from `planets_df`; what do you need to select the `rings` column then?
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# planets_df is pre-loaded in your workspace
# Select the rings variable from planets_df
rings_vector <-
# Print out rings_vector
```
`@solution`
```{r}
# planets_df is pre-loaded in your workspace
# Select the rings variable from planets_df
rings_vector <- planets_df$rings
# Print out rings_vector
rings_vector
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("rings_vector") %>% check_equal(incorrect_msg = "Have you correctly selected the `rings` variable from `planets_df`? Use `$rings`. Store the result as `rings_vector`.")
ex() %>% check_output_expr("rings_vector", missing_msg = "Don't forget to print out `rings_vector` after you've created it!")
success_msg("Great! Continue to the next exercise and discover yet another way of subsetting!")
```
---
## Only planets with rings (2)
```yaml
type: NormalExercise
key: 1581bf4667477f274188f4f637ec7fdc73659651
xp: 100
skills:
- 1
```
You probably remember from high school that some planets in our solar system have rings and others do not. Unfortunately you can not recall their names. Could R help you out?
If you type `rings_vector` in the console, you get:
```
[1] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE
```
This means that the first four observations (or planets) do not have a ring (`FALSE`), but the other four do (`TRUE`). However, you do not get a nice overview of the names of these planets, their diameter, etc. Let's try to use `rings_vector` to select the data for the four planets with rings.
`@instructions`
The code in the editor selects the `name` column of all planets that have rings. Adapt the code so that instead of only the `name` column, _all_ columns for planets that have rings are selected.
`@hint`
Remember that to select _all_ columns, you simply have to leave the columns part inside the `[ ]` empty! This means you'll need `[rings_vector, ]`.
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
rings_vector <- planets_df$rings
```
`@sample_code`
```{r}
# planets_df and rings_vector are pre-loaded in your workspace
# Adapt the code to select all columns for planets with rings
planets_df[rings_vector, "name"]
```
`@solution`
```{r}
# planets_df and rings_vector are pre-loaded in your workspace
# Adapt the code to select all columns for planets with rings
planets_df[rings_vector, ]
```
`@sct`
```{r}
msg <- "Do not remove or overwrite `planets_df` or `rings_vector`!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("rings_vector", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_output_expr('planets_df[rings_vector, ]', missing_msg = "Have you correctly adapted the code to select _all_ columns for the planets that have rings? You can use `planets_df[rings_vector, ]`. Make sure to include the comma here, it's crucial!")
success_msg("Wonderful! This is a rather tedious solution. The next exercise will teach you how to do it in a more concise way.")
```
---
## Only planets with rings but shorter
```yaml
type: NormalExercise
key: a4a8b72a74097196eb2f8a28b056987aae834565
xp: 100
skills:
- 1
```
So what exactly did you learn in the previous exercises? You selected a subset from a data frame (`planets_df`) based on whether or not a certain condition was true (rings or no rings), and you managed to pull out all relevant data. Pretty awesome! By now, NASA is probably already flirting with your CV ;-).
Now, let us move up one level and use the function [`subset()`](http://www.rdocumentation.org/packages/base/functions/subset). You should see the [`subset()`](http://www.rdocumentation.org/packages/base/functions/subset) function as a short-cut to do exactly the same as what you did in the previous exercises.
```
subset(my_df, subset = some_condition)
```
The first argument of [`subset()`](http://www.rdocumentation.org/packages/base/functions/subset) specifies the data set for which you want a subset. By adding the second argument, you give R the necessary information and conditions to select the correct subset.
The code below will give the exact same result as you got in the previous exercise, but this time, you didn't need the `rings_vector`!
```
subset(planets_df, subset = rings)
```
`@instructions`
Use `subset()` on `planets_df` to select planets that have a diameter smaller than Earth. Because the `diameter` variable is a relative measure of the planet's diameter w.r.t that of planet Earth, your condition is `diameter < 1`.
`@hint`
`subset(planets_df, subset = ...)` almost solves it; can you fill in the `...`?
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# planets_df is pre-loaded in your workspace
# Select planets with diameter < 1
```
`@solution`
```{r}
# planets_df is pre-loaded in your workspace
# Select planets with diameter < 1
subset(planets_df, subset = diameter < 1)
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_correct({
ex() %>% check_output_expr("subset(planets_df, subset = diameter < 1)", missing_msg = "Have you correctly specified the `subset = ...` part inside `subset()`. The condition in this case is `diameter < 1`. Simply print out the result.")
}, {
ex() %>% check_function("subset") %>% check_arg('x') %>% check_equal(incorrect_msg = "The first argument you pass to `subset()` should be `planets_df`.")
})
success_msg("Great! Not only is the `subset()` function more concise, it is probably also more understandable for people who read your code. Continue to the next exercise.");
```
---
## Sorting
```yaml
type: NormalExercise
key: 6a6fe74d3917c37380f7ac616ce084aa7814fb8a
xp: 100
skills:
- 1
```
Making and creating rankings is one of mankind's favorite affairs. These rankings can be useful (best universities in the world), entertaining (most influential movie stars) or pointless (best 007 look-a-like).
In data analysis you can sort your data according to a certain variable in the data set. In R, this is done with the help of the function [`order()`](http://www.rdocumentation.org/packages/base/functions/order).
[`order()`](http://www.rdocumentation.org/packages/base/functions/order) is a function that gives you the ranked position of each element when it is applied on a variable, such as a vector for example:
```
a <- c(100, 10, 1000)
order(a)
[1] 2 1 3
```
10, which is the second element in `a`, is the smallest element, so 2 comes first in the output of `order(a)`. 100, which is the first element in `a` is the second smallest element, so 1 comes second in the output of `order(a)`.
This means we can use the output of `order(a)` to reshuffle `a`:
```
a[order(a)]
[1] 10 100 1000
```
`@instructions`
Experiment with the [`order()`](http://www.rdocumentation.org/packages/base/functions/order) function in the console. Submit the answer when you are ready to continue.
`@hint`
Just play with the [`order()`](http://www.rdocumentation.org/packages/base/functions/order) function in the console!
`@pre_exercise_code`
```{r}
# no pec
```
`@sample_code`
```{r}
# Play around with the order function in the console
```
`@solution`
```{r}
# Play around with the order function in the console
```
`@sct`
```{r}
success_msg("Great! Now let's use the `order()` function to sort your data frame!")
```
---
## Sorting your data frame
```yaml
type: NormalExercise
key: fa88b58bf2cf62e0c181dfdcbdd2e1ddeac66807
xp: 100
skills:
- 1
```
Alright, now that you understand the [`order()`](http://www.rdocumentation.org/packages/base/functions/order) function, let us do something useful with it. You would like to rearrange your data frame such that it starts with the smallest planet and ends with the largest one. A sort on the `diameter` column.
`@instructions`
- Call `order()` on `planets_df$diameter` (the `diameter` column of `planets_df`). Store the result as `positions`.
- Now reshuffle `planets_df` with the `positions` vector as row indexes inside square brackets. Keep all columns. Simply print out the result.
`@hint`
- Use `order(planets_df$diameter)` to create `positions`.
- Now, you can use `positions` inside square brackets: `planets_df[...]`; can you fill in the `...`?
`@pre_exercise_code`
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
```
`@sample_code`
```{r}
# planets_df is pre-loaded in your workspace
# Use order() to create positions
positions <-
# Use positions to sort planets_df
```
`@solution`
```{r}
# planets_df is pre-loaded in your workspace
# Use order() to create positions
positions <- order(planets_df$diameter)
# Use positions to sort planets_df
planets_df[positions, ]
```
`@sct`
```{r}
msg = "Do not remove or overwrite the `planets_df` data frame!"
ex() %>% check_object("planets_df", undefined_msg = msg) %>% check_equal(incorrect_msg = msg)
ex() %>% check_object("positions") %>% check_equal(incorrect_msg = "Have you correctly calculated the `positions` variable? You can use `order(planets_df$diameter)`.")
ex() %>% check_output_expr("planets_df[positions,]",missing_msg = "Use `planets_df[positions, ]` to sort `planets_df`; the comma inside the square brackets is crucial!")
success_msg("Wonderful! This exercise concludes the chapter on data frames. Remember that data frames are extremely important in R, you will need them all the time. Another very often used data structure is the list. This will be the subject of the next chapter!")
```