Hello!
I am trying to pass user text into a function. The premise is to have a user type in the title ID (tt) of an IMDb listing. This will then pass into a function that will render a tree diagram. I am just running into an issue and I don't know if it is tasking 'too much'?
I am still wet behind the ears when it comes to shiny.
I have set the placeholder text for the input box to be the IMDb listing for good omens, so upon running it should start the function.
Here is the reprex:
library(rvest)
#> Loading required package: xml2
library(shiny)
library(stringr)
library(purrr)
#>
#> Attaching package: 'purrr'
#> The following object is masked from 'package:rvest':
#>
#> pluck
library(collapsibleTree)
library(htmlwidgets)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(stringr)
ui <- fluidPage(
titlePanel("IMDb: More Like This",windowTitle = "RMDb"),
sidebarLayout(
sidebarPanel(
textInput("tt", "Show Title ID", "tt1869454"),
br(),
),
mainPanel(
verbatimTextOutput("nText"),
plotOutput("scatter")
),
position = c("left","right")
)
)
server <- function(input, output){
# Create function for text to render
output$nText <- renderUI({
# Add below
url <- paste0("https://www.imdb.com/title/",input$tt,"/")
# Show Name for later
show_name <- url %>%
read_html() %>%
html_nodes("h1") %>%
html_text()
# This extracts the titles of the shows that are similar to the one you searched.
show_tree_show <- url %>%
read_html() %>%
html_nodes(".rec-title b") %>%
html_text(trim=T)
# This extracts the tt from the shows saved in the previous step
show_morelike <- url %>%
read_html() %>%
html_nodes(".rec_item,.rec_selected") %>%
html_attr("data-tconst")
# This makes a vector of all (12) of the URLs
urls <- paste0("https://www.imdb.com/title/",show_morelike,"/")
# Since we are working with 12 URLs we need to use the map function to apply this function over a list.
doThis <- function(i){
show_tree <- read_html(i) %>%
html_nodes(".rec-title b") %>%
html_text(trim=T)
}
# This runs the function with each URL in the vector
shows_tree_like_chr <- unlist(map(urls,doThis))
# This sets up the data how we need it by repeating each show title 12 times
show_tree_showlist <- NULL
for (i in 1:12){
show_tree_showlist <- rep(show_tree_show,each=12)
}
# The name of the dataframe should be changed to reflect the show you are working with.
show_tree <- data.frame(
show=show_tree_showlist,
shows_like_shows=shows_tree_like_chr
)
head(show_tree)
# End function
})
}
shinyApp(ui, server)
#>
#> Listening on http://127.0.0.1:7793
#> Warning: Error in if: argument is of length zero
Created on 2020-07-31 by the reprex package (v0.3.0)