DS4PS / cpp-526-fall-2019

Course material for CPP 526 Foundations of Data Science I
http://ds4ps.org/cpp-526-fall-2019
4 stars 4 forks source link

Lab 4: R does not seem to be recognizing the shiny functions #19

Open RickyDuran opened 5 years ago

RickyDuran commented 5 years ago

When trying to enter code into selectInput () and renderPlot ({}), I get the following errors:

selectInput( inputId= "team.widget",
             label= "Select A Team",
             choices= c( "Cincinnati Reds" , "Pittsburgh Pirates" , "Philadelphia Phillies" ,  "St. Louis Cardinals" , "Chicago White Sox" , "Detroit Tigers" , "Chicago Cubs" , "Boston Red Sox" , "New York Yankees" , "Cleveland Indians" ),
             selected= "Cincinnati Reds"   
           )

Error in selectInput(inputId = "team.widget", label = "Select A Team", : could not find function "selectInput"

Error in renderPlot({ : could not find function "renderPlot"

lecy commented 5 years ago

Have you installed Shiny?

I can't remember off the top of my head if you need to load Shiny in order to run chunks, or if it does it automatically when you include the shiny runtime command in the header.

lecy commented 5 years ago

Specifically, are you getting these errors when running chunks, or when knitting?

RickyDuran commented 5 years ago

I tried it without installing shiny and got the error, so added the code install.packages( "shiny" ) & install.packages( "flexdashboard" ) and still got the errors.

RickyDuran commented 5 years ago

Although, I also get this message when installing the packages `Installing package into �C:/Users/rduran3/Documents/R/win-library/3.6� (as �lib� is unspecified) trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/shiny_1.3.2.zip' Content type 'application/zip' length 4694929 bytes (4.5 MB) downloaded 4.5 MB

package ‘shiny’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in C:\Users\rduran3\AppData\Local\Temp\Rtmpe8MbkQ\downloaded_packages Installing package into �C:/Users/rduran3/Documents/R/win-library/3.6� (as �lib� is unspecified) trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.6/flexdashboard_0.5.1.1.zip' Content type 'application/zip' length 188026 bytes (183 KB) downloaded 183 KB

package ‘flexdashboard’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in C:\Users\rduran3\AppData\Local\Temp\Rtmpe8MbkQ\downloaded_packages`

lecy commented 5 years ago

Are you getting these errors when running chunks, or when knitting? I'm assuming chunks.

RickyDuran commented 5 years ago

After running the chunks.

lecy commented 5 years ago

Try knitting the file, and I believe it will work then.

It can't access the functions if not loaded. So although you don't need to include the typical load function for shiny in your RMD in order to knit:

library( shiny )

You would need to load shiny if you want to run chunks directly.

Try it out, though, and you will see why it doesn't make sense to run chunks with shiny functions.

RickyDuran commented 5 years ago

After rebooting R, I was able to get it going. Although now I am receiving the following message when trying to run my main chunk of code:

function (...) { if (length(outputArgs) != 0 && !hasExecuted$get()) { warning("Unused argument: outputArgs. The argument outputArgs is only ", "meant to be used when embedding snippets of Shiny code in an ", "R Markdown code chunk (using runtime: shiny). When running a ", "full Shiny app, please set the output arguments directly in ", "the corresponding output function of your UI code.") hasExecuted$set(TRUE) } if (is.null(formals(origRenderFunc))) origRenderFunc() else origRenderFunc(...) } <bytecode: 0x00000296ece2c288> <environment: 0x00000296f29f2a28> attr(,"class") [1] "shiny.render.function" "function"
attr(,"outputFunc") function (outputId, width = "100%", height = "400px", click = NULL, dblclick = NULL, hover = NULL, hoverDelay = NULL, hoverDelayType = NULL, brush = NULL, clickId = NULL, hoverId = NULL, inline = FALSE) { res <- imageOutput(outputId, width, height, click, dblclick, hover, hoverDelay, hoverDelayType, brush, clickId, hoverId, inline) res$attribs$class <- "shiny-plot-output" res } <bytecode: 0x00000296ece27b88>

attr(,"outputArgs") list() attr(,"hasExecuted") Public: clone: function (deep = FALSE) get: function () set: function (value) Private: value: FALSE
lecy commented 5 years ago

That's precisely what you should get. Recall that shiny functions convert R objects to HTML/Javascript (which is what you are seeing here).

This is why running shiny inside of chunks is not that helpful - you are better off running the whole document and testing the widgets that way.

RickyDuran commented 5 years ago

Perfect! Goal all my quirks figured out!

I did also receive an error for "trying to use CRAN without an error, but added ,repos = "http://cran.us.r-project.org" into the install code, and got it to go away. (Just a heads up if it comes up for anyone else.

install.packages( "shiny",repos = "http://cran.us.r-project.org" ) install.packages( "flexdashboard",repos = "http://cran.us.r-project.org" )

jmacost5 commented 5 years ago

I am getting errors too, what packages do I need for this lab? I get this message when I run the first chunklibrary( dplyr ) library( Lahman ) data( Teams ) ave.so <- Teams$SO / Teams$G

min and max values needed to create your plot window

ave.so.min <- min( ave.so, na.rm=T ) ave.so.max <- max( ave.so, na.rm=T )

the league average for each season

league.ave <- tapply( X=ave.so, INDEX=as.factor(year), FUN="mean", na.rm=T ) league.year <- as.numeric( names( league.ave ) ) Error in is.factor(x) : object 'year' not found and then I get this when I run my step 2 chunk: selectInput( inputId= "team.widget", # creates slot in input to hold values: input$your_inputId label= "Choose A Team", # title of the input widget choices= "Cincinnati Reds", "Pittsburgh Pirates" , "Philadelphia Phillies" , "St. Louis Cardinals", "Chicago White Sox", "Detroit Tigers Chicago Cubs", "Boston Red Sox","New York Yankees" , "Cleveland Indians" , # options for the user selected= "Cincinnati Reds" # set the default option )Error in selectInput(inputId = "team.widget", label = "Choose A Team", : unused arguments ("Detroit Tigers Chicago Cubs", "Boston Red Sox", "New York Yankees", "Cleveland Indians")

lecy commented 5 years ago

You need the shiny package. Note from the conversation above, to check progress you need to run the document, not a single chunk.

sunaynagoel commented 5 years ago

I tried to follow all the steps listed above. I did install Shiny Package, It did restart my R. When I try to run the file it gives me error that I need to install Shiny. When I try to run the chunk it gives me error that " could not find function SelectInput" Not sure what I am doing wrong?

lecy commented 5 years ago

Can you close down R Studio and open it back up, then try running the file.

If it doesn't run, then type library( shiny ) in the console. What do you get?

jmacost5 commented 5 years ago

I did install shinny

sunaynagoel commented 5 years ago

Can you close down R Studio and open it back up, then try running the file.

If it doesn't run, then type library( shiny ) in the console. What do you get?

@lecy I installed "shiny" in R console and it shows following message

install.packages( "shiny" ) trying URL 'https://cran.rstudio.com/bin/macosx/el-capitan/contrib/3.6/shiny_1.3.2.tgz' Content type 'application/x-gzip' length 4655011 bytes (4.4 MB)

downloaded 4.4 MB

The downloaded binary packages are in /var/folders/nr/ws6grp394l97p2_1ck4brfsw0000gn/T//Rtmp7wdAKN/downloaded_packages

After that I closed my R studio and opened it again. when I try to run my file, it gives following error. Loading required package: shiny Error in source(global_r, local = FALSE) : /Users/sunaynaagarwal/Downloads/Whole Body Global Regional Store Contact List 10.2013.xlsx:1:3: unexpected input 1: PK ^ Calls: -> do.call -> -> -> source Execution halted

lecy commented 5 years ago

@jmacost5 can you run the shiny widgets demo file?

https://cdn.rawgit.com/DS4PS/Data-Science-Class/53c986f1/TEMPLATES/ShinyWidgetsDemo.Rmd

sunaynagoel commented 5 years ago

Gives the same error

Loading required package: shiny Error in source(global_r, local = FALSE) : /Users/sunaynaagarwal/Downloads/Whole Body Global Regional Store Contact List 10.2013.xlsx:1:3: unexpected input 1: PK ^ Calls: -> do.call -> -> -> source Execution halted

lecy commented 5 years ago

@sunaynagoel You can load shiny using library without errors, but you can't run an RMD shiny file?

Or you are getting the error when loading shiny?

sunaynagoel commented 5 years ago

@lecy Yes I can load shiny function without errors but can't run RMD shiny file. I tried widget demo file, which is not running as well.

Not sure what is going wrong.

sunaynagoel commented 5 years ago

Can this mean anything? (Notice the last line in the message) When I call for details on installed.packages ("shiny"), it gives following message

Package LibPath Version Priority Depends Imports LinkingTo Suggests Enhances License License_is_FOSS License_restricts_use OS_type Archs MD5sum NeedsCompilation Built

What can I do on my part to do compilation? do I even need it?

lecy commented 5 years ago

I was going to suggest it might be a permissions problem accessing the file in the location it is currently saved. Can you try moving the file to the documents folder or desktop?

What is your OS? Mac or PC?

sunaynagoel commented 5 years ago

I have a mac. I am trying to look for my permission etc. I already reinstalled R. It is giving the same error. Now I am trying to update R studio.

sunaynagoel commented 5 years ago

My shiny is still not working but I have another question. For dynamic widgets, is it possible to create a vector to store all the dynamic choices of team names rather than entering them ourself?

sunaynagoel commented 5 years ago

I was going to suggest it might be a permissions problem accessing the file in the location it is currently saved. Can you try moving the file to the documents folder or desktop?

What is your OS? Mac or PC?

I think it is working now.

lecy commented 5 years ago

Regarding vectors of team names, there are some examples at the bottom of the lab.

You can also do things like:

t1 <- table( Teams$name )
t2 <- t1[ t1 > 100 ]  # teams that appear more than 100 times
names.vector <- names( t2 )

Or:

t1 <- table( Teams$name )
t2 <- head( sort( t1, decreasing=TRUE ), 25 )  # top 25 teams
names.vector <- names( t2 )
jmacost5 commented 5 years ago

https://cdn.rawgit.com/DS4PS/Data-Science-Class/53c986f1/TEMPLATES/ShinyWidgetsDemo.Rmd

I found my error. Working through the rest of the problems.

castower commented 5 years ago

Hello all,

I know on the original example from NYT when you hover over the data points in the background a label appears to identify the team and some other details. Should our finished version be able to do this? Mine currently does not. It just filters through showing different trendlines for each team and I think that's what the instructions asked for, but what to be sure that I'm not missing something.

Thanks!

lecy commented 5 years ago

Nope! At this point you are just using the widget to change the yellow trend line.

If you want to learn how to create hover-over graphics, though, you can check out the plotly package in R.

https://plot.ly/r/line-and-scatter/

castower commented 5 years ago

Thank you! One other thing I noticed is that for some reason it seems some of the data points are missing. For instance, in the example data points for the San Francisco Giants start in 1900, but mine only appear starting in 1960ish. Did I do something wrong with my input?

Here is code:

#Interactive code:
Teams$ave.so <- Teams$SO / Teams$G  # to make subsetable, add back to data frame
team.name <- input$Team

# adding season stats for the team:
dat.one.team <- filter( Teams, name == team.name )
points( x=dat.one.team$yearID, y=dat.one.team$ave.so, 
        pch=20,  cex=1.2, col="darkorange", type="o" )
lecy commented 5 years ago

Try this:

filter( Teams, name == "San Francisco Giants"  ) # or correct name as written in database

Do you get data points from 1900?

I suspect it is because the Giants changed their name, so the NYT maybe did some additional data standardization?

castower commented 5 years ago
filter( Teams, name == "San Francisco Giants"  )

The furthest it goes back is 1958, so they must have combined their old name with the current one.

castower commented 5 years ago

Looking at the data set again, it appears that they used the franchID variable instead of the team name because that goes back to 1883.

lecy commented 5 years ago

That makes sense. Did they change names or cities in 1958?

castower commented 5 years ago

Yes, they changed from the New York Giants to the San Francisco Giants. When I filtered the data that way, all of the points appeared.

I did the input as follows to correspond with the franchise ID:

selectInput( inputId= 'Team',
             label= 'Select Team',
            choices= c( list (`National League` = list("Arizona Diamondbacks" = "ARI", "Atlanta Braves" = "ATL", "Chicago Cubs" = "CHC", "Cincinnati Reds" = "CIN","Colorado Rockies" = "COL","Houston Astros" = "HOU", "Los Angeles Dodgers" = "LAD", "Miami Marlins" = "FLR","Milwaukee Brewers" = "MIL", "New York Mets" = "NYM", "Philadelphia Phillies" = "PHI", "Pittsburgh Pirates" = "PIT", "San Diego Padres" = "SDP", "San Francisco Giants" = "SFG","St. Louis Cardinals" = "STL", "Washington Nationals" = "WSN"),
           `American League` = list("Baltimore Orioles" = "BAL", "Boston Red Sox" = "BOS", "Chicago White Sox" = "CHW", "Cleveland Indians" = "CLE", "Detroit Tigers" = "DET", "Kansas City Royals" = "KCR", "Los Angeles Angels of Anaheim" = "ANA", "Minnesota Twins" = "MIN", "New York Yankees" = "NYY", "Oakland Athletics" = "OAK", "Seattle Mariners" = "SEA", "Tampa Bay Rays" = "TBD", "Texas Rangers" = "TEX", "Toronto Blue Jays" = "TOR"))),
             selected= "SFG" 
           )

and then filtered by franchID:

team.name <- input$Team
dat.one.team <- filter( Teams, franchID == team.name)

The only thing I can't seem to figure out is how to make the graph display a custom label. Currently, with this setting:

text ( x=1905, y=8.3, col="darkorange", labels= team.name, cex=1, font=2, adj=0 )

my chart displays the franchise ID (for example SFG) and I'm wondering if there's a way to use the team name for the label?

I tried to use dat.one.team$name, but that loads all of the team names on the graph instead of just the name for the selected team. Do you know if there is any way to accomplish just displaying that one name instead of the variable name?

lecy commented 5 years ago

It's a little tricky. Try something like:

# american league only - need to add national league teams 
d1 <- list("Arizona Diamondbacks" = "ARI", "Atlanta Braves" = "ATL", "Chicago Cubs" = "CHC", "Cincinnati Reds" = "CIN","Colorado Rockies" = "COL","Houston Astros" = "HOU", "Los Angeles Dodgers" = "LAD", "Miami Marlins" = "FLR","Milwaukee Brewers" = "MIL", "New York Mets" = "NYM", "Philadelphia Phillies" = "PHI", "Pittsburgh Pirates" = "PIT", "San Diego Padres" = "SDP", "San Francisco Giants" = "SFG","St. Louis Cardinals" = "STL", "Washington Nationals" = "WSN")

d2 <- unlist(d1)

franchise.name <- names(d2)
franchise.id <- as.character( d2 )

Then something like:

text ( ... labels= franchise.name[ franchise.id == team.name ], ... )
castower commented 5 years ago

It's a little tricky. Try something like:

# american league only - need to add national league teams 
d1 <- list("Arizona Diamondbacks" = "ARI", "Atlanta Braves" = "ATL", "Chicago Cubs" = "CHC", "Cincinnati Reds" = "CIN","Colorado Rockies" = "COL","Houston Astros" = "HOU", "Los Angeles Dodgers" = "LAD", "Miami Marlins" = "FLR","Milwaukee Brewers" = "MIL", "New York Mets" = "NYM", "Philadelphia Phillies" = "PHI", "Pittsburgh Pirates" = "PIT", "San Diego Padres" = "SDP", "San Francisco Giants" = "SFG","St. Louis Cardinals" = "STL", "Washington Nationals" = "WSN")

d2 <- unlist(d1)

franchise.name <- names(d2)
franchise.id <- as.character( d2 )

Then something like:

text ( ... labels= franchise.name[ franchise.id == team.name ], ... )

That worked! Thank you so much!

jmacost5 commented 5 years ago

I am not understanding how to program the code to go to the specific widget. The Chicago Reds is the only one showing up and I don't understand how make the other teams populate other than doing the same function copy and paste the same thing for each team and then they would all populate on the main screen. Also I do not understand how to get the widget to link to the line plotted, here is my code

Teams$ave.so <- Teams$SO / Teams$G  # to make subsetable, add back to data frame
one.team <- filter( Teams, name == "Cincinnati Reds" )
points( x=one.team$yearID, y=one.team$ave.so, type="b", pch=19, col="darkorange4" )
team.name <- "Cincinnati Reds" # only place it appears
dat.one.team <- filter( Teams, name == team.name )
points( x=dat.one.team$yearID, y=dat.one.team$ave.so, 
        pch=20,  cex=1.2, col="goldenrod1", type="b" )
segments( x0=1900, y0=8.3, x1=1904, y1=8.32, col="goldenrod1", lwd = 1.5 )
points(  league.year, league.ave, col="goldenrod1", pch=20, cex=1.2 )
text ( x=1915, y=8.3, col="goldenrod1", labels=team.name, cex=0.8 )

Do I need to add a variable? Do I need to change the "Cincinnati Reds" to something else?

lecy commented 5 years ago

@jmacost5 Read the section Adding a Team Trend to the Graph on the lab instructions.

https://ds4ps.org/cpp-526-fall-2019/LABS/lab-04-instructions.html

jmacost5 commented 5 years ago

So for the team.name function I need to put team.name <- input$my_widget_id # input widget value in order for it to work? Do I need to put it under the choices c(...) and list the teams?

jmacost5 commented 5 years ago

I am sorry I read it through a few times and I am just not understanding because I am confused if I put in the code, neither work

lecy commented 5 years ago

team.name is just a placeholder variable for whichever team the user has selected.

The widget values are stored on the input object at the name slot that you designate (inputID= on the selectInput() function).

You are assigning the user selection to the variable. Then using the variable in place of a specific team name in your code.

lecy commented 5 years ago

What did you name your widget? input$my_widget_id

jmacost5 commented 5 years ago

no I named it "team.widget", so when I put that in it shows the"team.widget" and when I click on the different options it does not put the trend lines in for the teams.

selectInput( inputId= "team.widget",   # creates slot in input to hold values: input$your_inputId
             label= "Select A Team",     # title of the input widget
             choices= c("Cincinnati Reds", "Pittsburgh Pirates", "St. Louis Cardinals"  , "Chicago White Sox", "Detroit Tigers", "Chicago Cubs", "Boston Red Sox", "New York Yankees","Cleveland Indians", "Arizona Dimondbacks"), # options for the user
             selected= "Cincinnati Reds"   # set the default option
           )
team.name <- "team.widget" # input widget value
Teams$ave.so <- Teams$SO / Teams$G  # to make subsetable, add back to data frame
one.team <- filter( Teams, name == team.name )
points( x=one.team$yearID, y=one.team$ave.so, type="b", pch=19, col="darkorange4" )
dat.one.team <- filter( Teams, name == team.name )
points( x=dat.one.team$yearID, y=dat.one.team$ave.so, 
        pch=20,  cex=1.2, col="goldenrod1", type="b" )
segments( x0=1900, y0=8.3, x1=1904, y1=8.32, col="goldenrod1", lwd = 1.5 )
points(  league.year, league.ave, col="goldenrod1", pch=20, cex=1.2 )
text ( x=1915, y=8.3, col="goldenrod1", labels=team.name, cex=0.8 )
lecy commented 5 years ago

Try:

team.name <- input$team.widget

Also, please format your questions with markdown. I'm having a hard time separating code and text.

lecy commented 5 years ago

Review the notes on Shiny - the shiny functions work a little different than others.

https://github.com/DS4PS/cpp-526-fall-2019/raw/master/lectures/shiny-widgets.pdf

And look at the code for the input widgets in the demo file. That would probably help clarify.

https://cdn.rawgit.com/DS4PS/Data-Science-Class/53c986f1/TEMPLATES/ShinyWidgetsDemo.Rmd

katiegentry07 commented 5 years ago

When I try to run the document, it gives me the following error:

Error in yaml::yaml.load(..., eval.expr = TRUE) : 
  Scanner error: while scanning for the next token at line 3, column 7 found character that cannot start any token at line 3, column 7
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted

It gives me the same error when I've tried to run the demo. Any advice?

lecy commented 5 years ago

I searched for "Error in yaml::yaml.load(..., eval.expr = TRUE) :" and here is what comes up:

https://community.rstudio.com/t/error-in-yaml-yaml-load-eval-expr-true-unused-argument-eval-expr-true-calls-anonymous-parse-yaml-front-matter-yaml-load-anonymous-execution-halted/27080/2

You need to update yaml, rmarkdown, and knitr package :package: . One of them is too old to work with the other.

Under tools you can search for package updates.

katiegentry07 commented 5 years ago

Thank you! I reinstalled the latest package of R which seemed to help.

I'm also having an error in this set of pre-loaded code into the RMD document stating that the object 'year' cannot be found. I'm assuming it is in the second to last line, but cannot figure out where I'm going wrong.

library( dplyr )
library( Lahman )
data( Teams )
ave.so <- Teams$SO / Teams$G

# min and max values needed to create your plot window 
ave.so.min <- min( ave.so, na.rm=T )
ave.so.max <- max( ave.so, na.rm=T )

# the league average for each season
league.ave <- tapply (x=ave.so, INDEX = as.factor (year), FUN="mean", na.rm=T)
league.year <- as.numeric( names( league.ave ) )
lecy commented 5 years ago

If you look back at Lab-03 you can see where the year variable is created.

ave.so <- Teams$SO / Teams$G  # average strike-outs per game each season 
year <- Teams$yearID

(I just updated the template to include that, thanks for pointing it out)

Note, though, that you need to reference yearID inside of the Teams data frame if you are subsetting the data. After filtering Teams here the vector year will still be the original size, and dat.one.team$yearID will be the length of the specific team you have selected.

# adding season stats for the team:
dat.one.team <- filter( Teams, name == team.name )
points( x=dat.one.team$yearID, y=dat.one.team$ave.so, 
        pch=20,  cex=1.2, col="goldenrod1", type="b" )