library(rvest)
library(stringr)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ purrr   0.3.5 
## ✔ tibble  3.1.8      ✔ dplyr   1.0.10
## ✔ tidyr   1.2.1      ✔ forcats 0.5.2 
## ✔ readr   2.1.3      
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter()         masks stats::filter()
## ✖ readr::guess_encoding() masks rvest::guess_encoding()
## ✖ dplyr::lag()            masks stats::lag()
library(RColorBrewer)
library('ggplot2')
url <- 'http://www.imdb.com/search/title?count=100&release_date=2016,2016&title_type=feature'
webpage <- read_html(url)

Selecting rankings

rank_data_html <- html_nodes(webpage,'.text-primary')
rank_data <- html_text(rank_data_html)
head(rank_data)
## [1] "1." "2." "3." "4." "5." "6."

Preprocessing data to convert to numerical format

rank_data<-as.numeric(rank_data)
head(rank_data)
## [1] 1 2 3 4 5 6

Scraping titles

title_data_html <- html_nodes(webpage,'.lister-item-header a')
title_data <- html_text(title_data_html)
head(title_data)
## [1] "Terrifier"       "Suicide Squad"   "Silence"         "Hush"           
## [5] "The Conjuring 2" "Split"

Scraping and preprocessing the movie description

description_data_html <- html_nodes(webpage,'.ratings-bar+ .text-muted')
description_data <- html_text(description_data_html)
head(description_data)
## [1] "\nOn Halloween night, Tara Heyes finds herself as the obsession of a sadistic murderer known as Art the Clown."                                                                       
## [2] "\nA secret government agency recruits some of the most dangerous incarcerated super-villains to form a defensive task force. Their first mission: save the world from the apocalypse."
## [3] "\nIn the 17th century, two Portuguese Jesuit priests travel to Japan in an attempt to locate their mentor, who is rumored to have committed apostasy, and to propagate Catholicism."  
## [4] "\nA deaf and mute writer who retreated into the woods to live a solitary life must fight for her life in silence when a masked killer appears at her window."                         
## [5] "\nEd and Lorraine Warren travel to North London to help a single mother raising four children alone in a house plagued by a supernatural spirit."                                     
## [6] "\nThree girls are kidnapped by a man with a diagnosed 23 distinct personalities. They must try to escape before the apparent emergence of a frightful new 24th."
description_data<-gsub("\n","",description_data)
head(description_data)
## [1] "On Halloween night, Tara Heyes finds herself as the obsession of a sadistic murderer known as Art the Clown."                                                                       
## [2] "A secret government agency recruits some of the most dangerous incarcerated super-villains to form a defensive task force. Their first mission: save the world from the apocalypse."
## [3] "In the 17th century, two Portuguese Jesuit priests travel to Japan in an attempt to locate their mentor, who is rumored to have committed apostasy, and to propagate Catholicism."  
## [4] "A deaf and mute writer who retreated into the woods to live a solitary life must fight for her life in silence when a masked killer appears at her window."                         
## [5] "Ed and Lorraine Warren travel to North London to help a single mother raising four children alone in a house plagued by a supernatural spirit."                                     
## [6] "Three girls are kidnapped by a man with a diagnosed 23 distinct personalities. They must try to escape before the apparent emergence of a frightful new 24th."

Scraping and preprocessing the movie runtime

runtime_data_html <- html_nodes(webpage,'.text-muted .runtime')
runtime_data <- html_text(runtime_data_html)
head(runtime_data)
## [1] "85 min"  "123 min" "161 min" "82 min"  "134 min" "117 min"
runtime_data<-gsub(" min","",runtime_data)
runtime_data<-as.numeric(runtime_data)
head(runtime_data)
## [1]  85 123 161  82 134 117
length(runtime_data)
## [1] 100

Scraping and preprocessing the movie genre

genre_data_html <- html_nodes(webpage,'.genre')
genre_data <- html_text(genre_data_html)
head(genre_data)
## [1] "\nHorror, Thriller            "          
## [2] "\nAction, Adventure, Fantasy            "
## [3] "\nDrama, History            "            
## [4] "\nHorror, Thriller            "          
## [5] "\nHorror, Mystery, Thriller            " 
## [6] "\nHorror, Thriller            "
genre_data<-gsub("\n","",genre_data)
genre_data<-gsub(" ","",genre_data)

Taking only the first genre of each movie and converting each genre from text to factor

genre_data<-gsub(",.*","",genre_data)
genre_data<-as.factor(genre_data)
head(genre_data)
## [1] Horror Action Drama  Horror Horror Horror
## 9 Levels: Action Adventure Animation Biography Comedy Crime Drama ... Horror

Scraping and preprocessing the IMDB rating

rating_data_html <- html_nodes(webpage,'.ratings-imdb-rating strong')
rating_data <- html_text(rating_data_html)
head(rating_data)
## [1] "5.6" "5.9" "7.2" "6.6" "7.3" "7.3"
rating_data<-as.numeric(rating_data)
head(rating_data)
## [1] 5.6 5.9 7.2 6.6 7.3 7.3

Scraping and preprocessing the votes section

votes_data_html <- html_nodes(webpage,'.sort-num_votes-visible span:nth-child(2)')
votes_data <- html_text(votes_data_html)
head(votes_data)
## [1] "47,604"  "710,171" "119,435" "149,202" "292,206" "532,800"
votes_data<-gsub(",","",votes_data)
votes_data<-as.numeric(votes_data)
head(votes_data)
## [1]  47604 710171 119435 149202 292206 532800

Scraping and preprocessing the directors data

directors_data_html <- html_nodes(webpage,'.text-muted+ p a:nth-child(1)')
#converting the directors data to text
directors_data <- html_text(directors_data_html)

#looking at the directors data
head(directors_data)
## [1] "Damien Leone"       "David Ayer"         "Martin Scorsese"   
## [4] "Mike Flanagan"      "James Wan"          "M. Night Shyamalan"
#Converting directors data into factors
directors_data<-as.factor(directors_data)
length(directors_data)
## [1] 100

Scraping and preprocessing the actors section

actors_data_html <- actors_data_html <- html_nodes(webpage,'.mode-advanced:nth-child(40) .lister-item-content a:nth-child(1) , .lister-item-content .ghost+ a')
actors_data <- html_text(actors_data_html)


#Let's have a look at the actors data
head(actors_data)
## [1] "Jenna Kanell"       "Will Smith"         "Andrew Garfield"   
## [4] "John Gallagher Jr." "Vera Farmiga"       "James McAvoy"
#Data-Preprocessing: converting actors data into factors
actors_data<-as.factor(actors_data)
length(actors_data)
## [1] 102
print(actors_data)
##   [1] Jenna Kanell         Will Smith           Andrew Garfield     
##   [4] John Gallagher Jr.   Vera Farmiga         James McAvoy        
##   [7] Andrew Garfield      Kim Min-hee          Ryan Gosling        
##  [10] Matthew McConaughey  Amy Adams            Auli'i Cravalho     
##  [13] Anna Kendrick        Ryan Reynolds        Gong Yoo            
##  [16] Russell Crowe        Felicity Jones       Chris Pine          
##  [19] Eva Green            Brian Cox            Ginnifer Goodwin    
##  [22] Ryunosuke Kamiki     Denzel Washington    Amy Adams           
##  [25] Melissa McCarthy     Alexander Skarsgård  Emilia Clarke       
##  [28] Jennifer Lawrence    Elizabeth Reaser     Taraji P. Henson    
##  [31] Stephen Lang         Jun Kunimura         Eddie Redmayne      
##  [34] Casey Affleck        Kate Bosworth        Teresa Palmer       
##  [37] John Goodman         Tom Cruise           Seth Rogen          
##  [40] 1                    X                    Andrew Ervin        
##  [43] Michelle Williams    John Krasinski       Samantha Robinson   
##  [46] Natalya Anisimova    Ben Affleck          Ben Affleck         
##  [49] Chris Evans          Erika Linder         Liam Hemsworth      
##  [52] Brenton Thwaites     Michael Keaton       James McAvoy        
##  [55] Elle Fanning         Mahershala Ali       Benedict Cumberbatch
##  [58] Matt Damon           Neel Sethi           Jonah Hill          
##  [61] Garance Marillier    Nia Vardalos         Emily Blunt         
##  [64] Sacha Baron Cohen    Viggo Mortensen      Travis Fimmel       
##  [67] Mario Casas          Lily James           John Gallagher Jr.  
##  [70] Dane DeHaan          Mark Rylance         Keanu Reeves        
##  [73] Matthew McConaughey  Sam Neill            Dev Patel           
##  [76] Matthew McConaughey  Hailee Steinfeld     Suki Waterhouse     
##  [79] Emma Roberts         Malcolm McDowell     Chloë Grace Moretz  
##  [82] Mark Wahlberg        Charlie Hunnam       Matt Damon          
##  [85] Lauren Cohan         Michael Fassbender   Jesse Eisenberg     
##  [88] Mia Wasikowska       Louis C.K.           Mila Kunis          
##  [91] Brad Pitt            Robert De Niro       Jason Statham       
##  [94] Jack Black           Benjamin Walker      Blake Lively        
##  [97] Frank Grillo         Aaron Poole          Summer H. Howell    
## [100] Chris Pine           Denzel Washington    Tom Hanks           
## 92 Levels: 1 Aaron Poole Alexander Skarsgård Amy Adams ... X

Scraping and preprocessing the metascore section

ratings_bar_data <- html_nodes(webpage,'.ratings-bar') %>%
   html_text2()

#look at the ratings bar
head(ratings_bar_data)
## [1] "5.6\nRate this\n 1 2 3 4 5 6 7 8 9 10 5.6/10 X "              
## [2] "5.9\nRate this\n 1 2 3 4 5 6 7 8 9 10 5.9/10 X \n40 Metascore"
## [3] "7.2\nRate this\n 1 2 3 4 5 6 7 8 9 10 7.2/10 X \n79 Metascore"
## [4] "6.6\nRate this\n 1 2 3 4 5 6 7 8 9 10 6.6/10 X \n67 Metascore"
## [5] "7.3\nRate this\n 1 2 3 4 5 6 7 8 9 10 7.3/10 X \n65 Metascore"
## [6] "7.3\nRate this\n 1 2 3 4 5 6 7 8 9 10 7.3/10 X \n63 Metascore"
#extract the metascore and convert to number
metascore_data <- str_match(ratings_bar_data, "\\d{2} Metascore") %>%
  str_match("\\d{2}") %>%
  as.numeric()
length(metascore_data)
## [1] 100
metascore_data
##   [1] NA 40 79 67 65 63 71 85 94 59 81 81 55 65 73 70 65 88 57 65 78 81 54 67 60
##  [26] 44 51 41 65 74 71 81 66 96 68 58 76 47 66 NA 82 48 82 NA 44 51 75 42 32 25
##  [51] 66 52 51 99 72 58 77 57 81 37 48 44 72 32 NA 45 44 47 66 46 53 81 69 49 77
##  [76] 62 58 35 33 68 78 42 42 36 46 34 61 60 60 21 38 66 26 59 55 62 NA 68 79 74
summary(metascore_data)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##   21.00   47.00   62.00   60.36   72.50   99.00       5

Scraping and preprocessing the gross earnings

votes_bar_data <- html_nodes(webpage,'.sort-num_votes-visible') |>
html_text2()
head(votes_bar_data)
## [1] "Votes: 47,604"                    "Votes: 710,171 | Gross: $325.10M"
## [3] "Votes: 119,435 | Gross: $7.10M"   "Votes: 149,202"                  
## [5] "Votes: 292,206 | Gross: $102.47M" "Votes: 532,800 | Gross: $138.29M"
gross_data <- str_match(votes_bar_data, "\\$.+$") 
gross_data <- gsub("M","",gross_data)
gross_data <- substring(gross_data,2,6) |>
  as.numeric()
length(gross_data)
## [1] 100

Combining all the lists to form a data frame

movies_df<-data.frame(Rank = rank_data, Title = title_data, Description = description_data, Runtime = runtime_data,Genre = genre_data, Rating = rating_data, Metascore = metascore_data, Votes = votes_data, Gross_Earning_in_Mil = gross_data, Director = directors_data)

str(movies_df)
## 'data.frame':    100 obs. of  10 variables:
##  $ Rank                : num  1 2 3 4 5 6 7 8 9 10 ...
##  $ Title               : chr  "Terrifier" "Suicide Squad" "Silence" "Hush" ...
##  $ Description         : chr  "On Halloween night, Tara Heyes finds herself as the obsession of a sadistic murderer known as Art the Clown." "A secret government agency recruits some of the most dangerous incarcerated super-villains to form a defensive "| __truncated__ "In the 17th century, two Portuguese Jesuit priests travel to Japan in an attempt to locate their mentor, who is"| __truncated__ "A deaf and mute writer who retreated into the woods to live a solitary life must fight for her life in silence "| __truncated__ ...
##  $ Runtime             : num  85 123 161 82 134 117 139 145 128 108 ...
##  $ Genre               : Factor w/ 9 levels "Action","Adventure",..: 9 1 7 9 9 9 4 7 5 3 ...
##  $ Rating              : num  5.6 5.9 7.2 6.6 7.3 7.3 8.1 8.1 8 7.1 ...
##  $ Metascore           : num  NA 40 79 67 65 63 71 85 94 59 ...
##  $ Votes               : num  47604 710171 119435 149202 292206 ...
##  $ Gross_Earning_in_Mil: num  NA 325.1 7.1 NA 102.4 ...
##  $ Director            : Factor w/ 97 levels "Alessandro Carloni",..: 19 22 61 65 44 59 63 71 18 34 ...

Question 1: Based on the above data, which movie from which genre had the longest runtime?

filter to find max run time

#selecting the movies with the 5 highest run times
top_five<-movies_df |> 
  arrange(desc(Runtime)) |>
  top_n(5, Runtime)
head(top_five)
##   Rank                              Title
## 1    3                            Silence
## 2   32                        The Wailing
## 3   45 Batman v Superman: Dawn of Justice
## 4   47         Captain America: Civil War
## 5   68                A Cure for Wellness
##                                                                                                                                                                                                                               Description
## 1                                                       In the 17th century, two Portuguese Jesuit priests travel to Japan in an attempt to locate their mentor, who is rumored to have committed apostasy, and to propagate Catholicism.
## 2                                          Soon after a stranger arrives in a little village, a mysterious sickness starts spreading. A policeman, drawn into the incident, is forced to solve the mystery in order to save his daughter.
## 3 Batman is manipulated by Lex Luthor to fear Superman. Superman´s existence is meanwhile dividing the world and he is framed for murder during an international crisis. The heroes clash and force the neutral Wonder Woman to reemerge.
## 4                                                                                                                                      Political involvement in the Avengers' affairs causes a rift between Captain America and Iron Man.
## 5         An ambitious young executive is sent to retrieve his company's CEO from an idyllic but mysterious "wellness center" at a remote location in the Swiss Alps, but soon suspects that the spa's treatments are not what they seem.
##   Runtime  Genre Rating Metascore  Votes Gross_Earning_in_Mil        Director
## 1     161  Drama    7.2        79 119435                 7.10 Martin Scorsese
## 2     156  Drama    7.4        81  77370                   NA     Na Hong-jin
## 3     151 Action    6.5        44 741776               330.30     Zack Snyder
## 4     147 Action    7.8        75 829951               408.00   Anthony Russo
## 5     146  Drama    6.4        47 106694                 8.11  Gore Verbinski
#Plotting the movies with the 5 highest run times
ggplot(top_five, aes(x=fct_reorder(Title, Runtime), y=Runtime, fill=Genre)) +
  geom_col()+ 
    scale_fill_brewer(name= "Genre", palette = "Dark2")+
  geom_text(aes(label=paste(Runtime,"min", sep=" ")), size=3,hjust=.5, vjust=2.5, color="white")+
  theme(legend.title = element_text(size=6), legend.text = element_text(size=6), axis.text.x = element_text(angle = 45, hjust = 1), axis.text.y=element_blank(),
        axis.ticks.y=element_blank())+
  labs(x= "Title",
       y="Run time",
       subtitle="Title and Genre of Movies with the Top 5 runtimes",
       caption="Source: IMDB Feature Films, Released between 2016-01-01 and 2016-12-31")+
  scale_x_discrete(labels = function(x) str_wrap(x, width = 20))

The figure above shows that with a run time of 161 minutes, the movie, Silence in the Drama Genre has the longest.

Based on the above data, in the Runtime of 130-160 mins, which genre has the highest votes?

#Filtering movies with the highest votes among movies with run time 130-160
highestvotes<-movies_df|>
  filter(Runtime >= 130 & Runtime <= 160)
head(highestvotes)
##   Rank                        Title
## 1    5              The Conjuring 2
## 2    7                Hacksaw Ridge
## 3    8               The Handmaiden
## 4   17 Rogue One: A Star Wars Story
## 5   23        The Magnificent Seven
## 6   32                  The Wailing
##                                                                                                                                                                                                         Description
## 1                                                                    Ed and Lorraine Warren travel to North London to help a single mother raising four children alone in a house plagued by a supernatural spirit.
## 2 World War II American Army Medic Desmond T. Doss, serving during the Battle of Okinawa, refuses to kill people and becomes the first man in American history to receive the Medal of Honor without firing a shot.
## 3                                                                                                    A woman is hired as a handmaiden to a Japanese heiress, but secretly she is involved in a plot to defraud her.
## 4                                                   In a time of conflict, a group of unlikely heroes band together on a mission to steal the plans to the Death Star, the Empire's ultimate weapon of destruction.
## 5                                               Seven gunmen from a variety of backgrounds are brought together by a vengeful young widow to protect her town from the private army of a destructive industrialist.
## 6                    Soon after a stranger arrives in a little village, a mysterious sickness starts spreading. A policeman, drawn into the incident, is forced to solve the mystery in order to save his daughter.
##   Runtime     Genre Rating Metascore  Votes Gross_Earning_in_Mil       Director
## 1     134    Horror    7.3        65 292206               102.40      James Wan
## 2     139 Biography    8.1        71 571808                67.21     Mel Gibson
## 3     145     Drama    8.1        85 164453                 2.01 Park Chan-wook
## 4     133    Action    7.8        65 671134               532.10 Gareth Edwards
## 5     132    Action    6.9        54 223710                93.43  Antoine Fuqua
## 6     156     Drama    7.4        81  77370                   NA    Na Hong-jin
#Plotting movies with the highest votes among movies with run time 130-160
options(scipen=999)
ggplot(highestvotes, aes(Runtime, Votes, color=Genre)) +
  geom_point()+ 
    scale_color_brewer(name= "Genre", palette = "Dark2")+
  geom_text(aes(label=paste(Votes)), size=2,hjust=.5, vjust=2.5, color="black")+
  theme(legend.title = element_text(size=6), legend.text = element_text(size=6), axis.text.x = element_text(angle = 45, hjust = 1))+
  theme_bw()

  labs(x= "Run time",
       y="Number of votes",
       subtitle="Genres with highest votes among movies with runtime 130-160 mins",
       caption="Source: IMDB Feature Films, Released between 2016-01-01 and 2016-12-31")
## $x
## [1] "Run time"
## 
## $y
## [1] "Number of votes"
## 
## $subtitle
## [1] "Genres with highest votes among movies with runtime 130-160 mins"
## 
## $caption
## [1] "Source: IMDB Feature Films, Released between 2016-01-01 and 2016-12-31"
## 
## attr(,"class")
## [1] "labels"

The figure above shows that among movies with the run time of 130-160 mins, the action genre has the highest number of votes.

Question 3: Across all genres which genre has the highest average gross earnings in runtime 100 to 120.

#Calculating the highest average gross earnings genre among movies with run time 130-160
highest_average_gross<-movies_df|>
  filter(Runtime >= 100 & Runtime <= 120)|>
  group_by(Genre)|>
  summarize(avg_grossearnings=mean(Gross_Earning_in_Mil, na.rm=T))
head(highest_average_gross)
## # A tibble: 6 × 2
##   Genre     avg_grossearnings
##   <fct>                 <dbl>
## 1 Action                 89.2
## 2 Adventure             125. 
## 3 Animation             216. 
## 4 Biography              28.7
## 5 Comedy                 33.9
## 6 Crime                  51.2
#Plotting highest average gross earnings genre among movies with run time 130-160
ggplot(highest_average_gross, aes(avg_grossearnings, Genre, fill= Genre))+
  geom_col()+ 
  geom_text(aes(label=paste("$",round(avg_grossearnings, digits = 2),"M", sep="")), size=3,hjust=1, vjust=2, color="white")+
  theme(legend.position="none")+
    scale_fill_brewer(name="Genre", palette = "Dark2")+
  labs(x= "Average gross earnings (Million Dollars)",
       y="Genre",
       Title="Average gross earnings by genre among movies with run time 100-120 mins",
       caption="Source: IMDB Feature Films, Released between 2016-01-01 and 2016-12-31")

The figure above shows that across movies with run time 100 to 120 minutes, the genre with the highest gross earning was the animation genre.