forked from datacamp/courses-introduction-to-r
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchapter6.Rmd
More file actions
424 lines (307 loc) · 15.7 KB
/
chapter6.Rmd
File metadata and controls
424 lines (307 loc) · 15.7 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
---
title_meta : Chapter 6
title : Lists
description : Lists, as opposed to vectors, can hold components of different types, just like your to-do list at home or at work. This intro to R chapter will teach you how to create, name and subset these lists.
--- type:NormalExercise xp:100 skills:1 key:2afcdb6a76ec91bf266de9b2ac295d844d7bb004
## Lists, why would you need them?
Congratulations! At this point in the course you are already familiar with:
- **Vectors** (one dimensional array): can hold numeric, character or logical values. The elements in a vector all have the same data type.
- **Matrices** (two dimensional array): can hold numeric, character or logical values. The elements in a matrix all have the same data type.
- **Data frames** (two-dimensional objects): can hold numeric, character or logical values. Within a column all elements have the same data type, but different columns can be of different data type.
Pretty sweet for an R newbie, right? ;-)
*** =instructions
Click 'Submit Answer' to start learning everything about lists!
*** =hint
Just click the 'Submit Answer' button.
*** =pre_exercise_code
```{r}
# no pec
```
*** =sample_code
```{r}
# Just click the 'Submit Answer' button.
```
*** =solution
```{r}
# Just click the 'Submit Answer' button.
```
*** =sct
```{r}
success_msg("Ready, set, go! Continue to the next exercise.")
```
--- type:NormalExercise xp:100 skills:1 key:68f93c5c504616bd18876da52cd123277d56fc8b
## Lists, why would you need them? (2)
A **list** in R is similar to your to-do list at work or school: the different items on that list most likely differ in length, characteristic, type of activity that has to do be done, ...
A list in R allows you to gather a variety of objects under one name (that is, the name of the list) in an ordered way. These objects can be matrices, vectors, data frames, even other lists, etc. It is not even required that these objects are related to each other in any way.
You could say that a list is some kind super data type: you can store practically any piece of information in it!
*** =instructions
Click 'Submit Answer' to start the first exercise on lists.
*** =hint
Click 'Submit Answer' to start the first exercise on lists.
*** =pre_exercise_code
```{r}
# no pec
```
*** =sample_code
```{r}
# Click 'Submit Answer' to start the first exercise on lists.
```
*** =solution
```{r}
# Click 'Submit Answer' to start the first exercise on lists.
```
*** =sct
```{r}
success_msg("Cool. Let's get our hands dirty!")
```
--- type:NormalExercise xp:100 skills:1 key:4beee9cb532c889903218b49b83ab5ef133eac83
## Creating a list
Let us create our first list! To construct a list you use the function [`list()`](http://www.rdocumentation.org/packages/base/functions/list):
```
my_list <- list(comp1, comp2 ...)
```
The arguments to the list function are the list components. Remember, these components can be matrices, vectors, other lists, ...
*** =instructions
Construct a list, named `my_list`, that contains the variables `my_vector`, `my_matrix` and `my_df` as list components.
*** =hint
Use the [`list()`](http://www.rdocumentation.org/packages/base/functions/list) function with `my_vector`, `my_matrix` and `my_df` as arguments separated by a comma.
*** =pre_exercise_code
```{r}
# no pec
```
*** =sample_code
```{r}
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Construct list with these different elements:
my_list <-
```
*** =solution
```{r}
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Construct list with these different elements:
my_list <- list(my_vector, my_matrix, my_df)
```
*** =sct
```{r}
msg = "Do not remove or change the definition of the variables `my_vector`, `my_matrix` or `my_df`!"
test_object("my_vector", undefined_msg = msg, incorrect_msg = msg)
test_object("my_matrix", undefined_msg = msg, incorrect_msg = msg)
test_object("my_df", undefined_msg = msg, incorrect_msg = msg)
test_object("my_list",
incorrect_msg = "It looks like `my_list` does not contain the correct elements. Make sure to pass the variables `my_vector`, `my_matrix` and `my_df` to the `list()` function, separated by commas, in this order.")
success_msg("Wonderful! Head over to the next exercise.")
```
--- type:NormalExercise xp:100 skills:1 key:89dd0126568b1ff5a84033c571907a8a282245e4
## Creating a named list
Well done, you're on a roll!
Just like on your to-do list, you want to avoid not knowing or remembering what the components of your list stand for. That is why you should give names to them:
```
my_list <- list(name1 = your_comp1,
name2 = your_comp2)
```
This creates a list with components that are named `name1`, `name2`, and so on. If you want to name your lists after you've created them, you can use the `names()` function as you did with vectors. The following commands are fully equivalent to the assignment above:
```
my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")
```
*** =instructions
- Change the code of the previous exercise (see editor) by adding names to the components. Use for `my_vector` the name `vec`, for `my_matrix` the name `mat` and for `my_df` the name `df`.
- Print out `my_list` so you can inspect the output.
*** =hint
The first method of assigning names to your list components is the easiest. It starts like this:
```
my_list <- list(vec = my_vector)
```
Add the other two components in a similar fashion.
*** =pre_exercise_code
```{r}
# no pec
```
*** =sample_code
```{r}
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Adapt list() call to give the components names
my_list <- list(my_vector, my_matrix, my_df)
# Print out my_list
```
*** =solution
```{r}
# Vector with numerics from 1 up to 10
my_vector <- 1:10
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
# Adapt list() call to give the components names
my_list <- list(vec = my_vector, mat = my_matrix, df = my_df)
# Print out my_list
my_list
```
*** =sct
```{r}
msg = "Do not remove or change the definiton of the variables `my_vector`, `my_matrix` or `my_df`!"
test_object("my_vector", undefined_msg = msg, incorrect_msg = msg)
test_object("my_matrix", undefined_msg = msg, incorrect_msg = msg)
test_object("my_df", undefined_msg = msg, incorrect_msg = msg)
test_object("my_list",
incorrect_msg = "It looks like `my_list` does not contain the correct elements.")
test_object("my_list", eq_condition = "equal",
incorrect_msg = "It looks like `my_list` does not contain the correct naming for the components. Make sure you use the names `vec`, `mat` and `df`, respectively. Check out the hint if you're struggling.");
test_output_contains("my_list", incorrect_msg = "Don't forget to print `my_list` to the console! Simply add `my_list` on a new line in the editor.")
success_msg("Great! Not only do you know how to construct lists now, you can also name them; a skill that will prove most useful in practice. Continue to the next exercise.")
```
--- type:NormalExercise xp:100 skills:1 key:19fd17cc792ef870c1558b3a9bae08c1d1e3acae
## Creating a named list (2)
Being a huge movie fan (remember your job at LucasFilms), you decide to start storing information on good movies with the help of lists.
Start by creating a list for the movie "The Shining". We have already created the variables `mov`, `act` and `rev` in your R workspace. Feel free to check them out in the console.
*** =instructions
Complete the code on the right to create `shining_list`; it contains three elements:
- moviename: a character string with the movie title (stored in `mov`)
- actors: a vector with the main actors' names (stored in `act`)
- reviews: a data frame that contains some reviews (stored in `rev`)
Do not forget to name the list components accordingly (names are moviename, actors and reviews).
*** =hint
`shining_list <- list(moviename = mov)` is only part of the solution; it's your job to also add `act` and `rev` to the list, with the appropriate names.
*** =pre_exercise_code
```{r}
mov <- "The Shining"
act <- c("Jack Nicholson","Shelley Duvall","Danny Lloyd","Scatman Crothers","Barry Nelson")
sources <- c("IMDb1","IMDb2","IMDb3")
comments <- c("Best Horror Film I Have Ever Seen","A truly brilliant and scary film from Stanley Kubrick","A masterpiece of psychological horror")
scores <- c(4.5,4,5)
rev <- data.frame(scores, sources, comments)
rm(scores, sources, comments)
```
*** =sample_code
```{r}
# The variables mov, act and rev are available
# Finish the code to build shining_list
shining_list <- list(moviename = mov)
```
*** =solution
```{r}
# The variables mov, act and rev are available
# Finish the code to build shining_list
shining_list <- list(moviename = mov, actors = act, reviews = rev)
```
*** =sct
```{r}
msg = "Do not remove or change the definition of the pre-set variables!"
lapply(c("mov", "rev", "act"), test_object, undefined_msg = msg, incorrect_msg = msg)
test_object("shining_list",
incorrect_msg = "It looks like `shining_list` does not contain the correct elements: the first element should be `mov`, the second element `act`, and the third `rev`.")
test_object("shining_list", eq_condition = "equal",
incorrect_msg = "It looks like `shining_list` does not contain the correct naming for the components: name the first element `moviename`, the second element `actors`, and the third element `reviews`.");
success_msg("Wonderful! You now know how to construct and name lists. As in the previous chapters, let's look at how to select elements for lists. Head over to the next exercise")
```
--- type:NormalExercise xp:100 skills:1 key:1ef3278944562caef64b9927dd2ddb6ee52334cd
## Selecting elements from a list
Your list will often be built out of numerous elements and components. Therefore, getting a single element, multiple elements, or a component out of it is not always straightforward.
One way to select a component is using the numbered position of that component. For example, to "grab" the first component of `shining_list` you type
```
shining_list[[1]]
```
A quick way to check this out is typing it in the console. Important to remember: to select elements from vectors, you use single square brackets: `[ ]`. Don't mix them up!
You can also refer to the names of the components, with `[[ ]]` or with the `$` sign. Both will select the data frame representing the reviews:
```
shining_list[["reviews"]]
shining_list$reviews
```
Besides selecting components, you often need to select specific elements out of these components. For example, with `shining_list[[2]][1]` you select from the second component, `actors` (`shining_list[[2]]`), the first element (`[1]`). When you type this in the console, you will see the answer is Jack Nicholson.
*** =instructions
- Select from `shining_list` the vector representing the actors. Simply print out this vector.
- Select from `shining_list` the second element in the vector representing the actors. Do a printout like before.
*** =hint
- To select the vector representing the actors, you can use `$actors`.
- To select the third element in the vector representing the actors, you use `shining_list$actors[3]`. What needs to change to select the second element?
*** =pre_exercise_code
```{r}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/shining_list.RData"))
```
*** =sample_code
```{r}
# shining_list is already pre-loaded in the workspace
# Print out the vector representing the actors
# Print the second element of the vector representing the actors
```
*** =solution
```{r}
# shining_list is already pre-loaded in the workspace
# Print out the vector representing the actors
shining_list$actors
# Print the second element of the vector representing the actors
shining_list$actors[2]
```
*** =sct
```{r}
msg <- "Do not remove or change the definition of `shining_list`, which is pre-loaded in the workspace!"
test_object("shining_list", undefined_msg = msg, incorrect_msg = msg)
test_output_contains("shining_list$actors", incorrect_msg = "Have you correctly selected and printed out the vector representing actors? You can use `shining_list$actors`, for example.")
test_output_contains("shining_list$actors[2]", incorrect_msg = "To select the second actor from the vector representing actors, you should chain your selections: `shining_list$actors` represents the actors, so you can add a `[2]` to select the second element.")
success_msg("Great! Selecting elements from lists is rather easy isn't it? Continue to the next exercise.")
```
--- type:NormalExercise xp:100 skills:1 key:ca3f7b71504ff93940cf65889d406a58c5b0019c
## Adding more movie information to the list
Being proud of your first list, you shared it with the members of your movie hobby club. However, one of the senior members, a guy named M. McDowell, noted that you forgot to add the release year. Given your ambitions to become next year's president of the club, you decide to add this information to the list.
To conveniently add elements to lists you can use the [`c()`](http://www.rdocumentation.org/packages/base/functions/c) function, that you also used to build vectors:
```
ext_list <- c(my_list , my_val)
```
This will simply extend the original list, `my_list`, with the component `my_val`. This component gets appended to the end of the list.
If you want to give the new list item a name, you just add the name as you did before:
```
ext_list <- c(my_list, my_name = my_val)
```
*** =instructions
- Complete the code below such that an item named `year` is added to the `shining_list` with the value 1980. Assign the result to `shining_list_full`.
- Finally, have a look at the structure of `shining_list_full` with the [`str()`](http://www.rdocumentation.org/packages/utils/functions/str) function.
*** =hint
Have a look at the example code in the exercise assignment. Maybe this can help you start:
```
shining_list <- c(shining_list, ...)
```
You still have to add some code where the three dots are.
*** =pre_exercise_code
```{r, eval = FALSE}
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/shining_list.RData"))
```
*** =sample_code
```{r}
# shining_list, the list containing movie name, actors and reviews, is pre-loaded in the workspace
# We forgot something; add the year to shining_list
shining_list_full <-
# Have a look at shining_list_full
```
*** =solution
```{r}
# shining_list, the list containing movie name, actors and reviews, is pre-loaded in the workspace
# Use c() to add a year to shining_list
shining_list_full <- c(shining_list, year = 1980)
# Have a look at shining_list_full
str(shining_list_full)
```
*** =sct
```{r}
msg = "Do not remove or change the definition of `shining_list`, which is pre-loaded in the workspace!"
test_object("shining_list", undefined_msg = msg, incorrect_msg = msg)
test_object("shining_list_full", eq_condition = "equal",
incorrect_msg = paste("Have you correctly extended `shining_list` with an element named `year`,",
"whose value is 1980? You can use `c(shining_list, year = 1980)`"))
test_function("str", "object", incorrect_msg = "Don't forget to display the structure of `shining_list_full` with `str()`.")
success_msg("Great! This was the last exercise on R lists! You now have a solid basis in the R programming language, but there's so much more to learn. Check out all the other DataCamp courses and become a true data science expert!")
```