18.4 Chapter 7: Indexing vectors with []

Table 18.2: Some of my favorite movies
movie year boxoffice genre time rating
Whatever Works 2009 35.0 Comedy 92 PG-13
It Follows 2015 15.0 Horror 97 R
Love and Mercy 2015 15.0 Drama 120 R
The Goonies 1985 62.0 Adventure 90 PG
Jiro Dreams of Sushi 2012 3.0 Documentary 81 G
There Will be Blood 2007 10.0 Drama 158 R
Moon 2009 321.0 Science Fiction 97 R
Spice World 1988 79.0 Comedy -84 PG-13
Serenity 2005 39.0 Science Fiction 119 PG-13
Finding Vivian Maier 2014 1.5 Documentary 84 Unrated
  1. Create new data vectors for each column.
movie <- c("Whatever Works", "It Follows", "Love and Mercy", 
             "The Goonies", "Jiro Dreams of Sushi",
             "There Will be Blood", "Moon", 
             "Spice World", "Serenity", "Finding Vivian Maier")

year <- c(2009, 2015, 2015, 1985, 2012, 2007, 2009, 1988, 2005, 2014)

boxoffice <- c(35, 15, 15, 62, 3, 10, 321, 79, 39, 1.5)

genre <- c("Comedy", "Horror", "Drama", "Adventure", "Documentary", 
           "Drama", "Science Fiction", "Comedy", "Science Fiction", 
           "Documentary")

time <- c(92, 97, 120, 90, 81, 158, 97, -84, 119, 84)

rating <- c("PG-13", "R", "R", "PG", "G", "R", "R", 
            "PG-13", "PG-13", "Unrated")
  1. What is the name of the 10th movie in the list?
movie[10]
## [1] "Finding Vivian Maier"
  1. What are the genres of the first 4 movies?
genre[1:4]
## [1] "Comedy"    "Horror"    "Drama"     "Adventure"
  1. Some joker put Spice World in the movie names – it should be ``The Naked Gun’’ Please correct the name.
movie[movie == "Spice World"] <- "The Naked Gun"
  1. What were the names of the movies made before 1990?
movie[year < 1990]
## [1] "The Goonies"   "The Naked Gun"
  1. How many movies were Dramas? What percent of the 10 movies were Comedies?
sum(genre == "Drama")
## [1] 2

mean(genre == "Comedy")
## [1] 0.2
  1. One of the values in the time vector is invalid. Convert any invalid values in this vector to NA. Then, calculate the mean movie time
time[time < 0] <- NA

mean(time, na.rm = TRUE)
## [1] 104
  1. What were the names of the Comedy movies? What were their boxoffice totals? (Two separate questions)
movie[genre == "Comedy"]
## [1] "Whatever Works" "The Naked Gun"

boxoffice[genre == "Comedy"]
## [1] 35 79
  1. What were the names of the movies that made less than $50 Million dollars AND were Comedies?
movie[boxoffice < 50 & genre == "Comedy"]
## [1] "Whatever Works"
  1. What was the median boxoffice revenue of movies rated either G or PG?
median(boxoffice[rating %in% c("G", "PG")])
## [1] 32

# OR

median(boxoffice[rating == "G" | rating == "PG"])
## [1] 32
  1. What percent of the movies were either rated R OR were comedies?
mean(rating == "R" | genre == "Comedy")
## [1] 0.6