-
Notifications
You must be signed in to change notification settings - Fork 1
/
Lists
76 lines (54 loc) · 1.96 KB
/
Lists
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
Chapter 6
Lists, why would you need them?
# Just submit the answer
Lists, why would you need them? (2)
# Just submit the answer to start the first exercise on lists.
Creating a list
# Vector with numerics from 1 up to 10
my_vector <- 1:10
my_vector
# Matrix with numerics from 1 up to 9
my_matrix <- matrix(1:9, ncol = 3)
my_matrix
# First 10 elements of the built-in data frame mtcars
my_df <- mtcars[1:10,]
my_df
# Construct list with these different elements:
my_list <- list(my_vector, my_matrix,my_df)
Creating a named list
# 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)
#Alternative way
#my_list <- list(my_vector, my_matrix, my_df)
#names(my_list) <- c("vec", "mat","df")
# Print out my_list
my_list
Creating a named list (2)
# The variables mov, act and rev are available
# Finish the code to build shining_list
shining_list <- list(moviename = mov, actors=act, reviews=rev)
shining_list
Selecting elements from a list
# shining_list is already pre-loaded in the workspace
shining_list
# Print out the vector representing the actors
shining_list[[2]]
# Print the second element of the vector representing the actors
shining_list[[2]][2]
Creating a new list for another movie
# Use the table from the exercise to define the comments and scores vectors
scores <- c(4.6, 5, 4.8, 5, 4.2)
comments <- c("I would watch it again", "Amazing!", "I liked it", "One of the best movies", 'Fascinating plot')
# Save the average of the scores vector as avg_review
avg_review=mean(scores)
# Combine scores and comments into the reviews_df data frame
reviews_df=data.frame(scores,comments)
# Create and print out a list, called departed_list
departed_list<- list(movie_title, movie_actors, reviews_df, avg_review)
departed_list