server.R

Let's take a quick look at the server.R file, shown in the following code:

function(input, output) { 
  output$textDisplay <- renderText({ 
    paste0("Title:'", input$comment, 
      "'. There are ", nchar(input$comment), 
      " characters in this." 
    ) 
  }) 
 
  output$plotDisplay <- renderPlot({ 
    par(bg = "#ecf1ef") # set the background color 
    plot(poly(1:100, as.numeric(input$graph)), type = "l", 
      ylab="y", xlab="x") 
  }) 
} 

Text handling is done as before. You'll note that the renderPlot() function begins by setting the background color to the same as the page itself (par(bg = "#ecf1ef"); for more graphical options in R, see ?par). You don't have to do this, but the graph's background will be visible as a big white square if you don't.

The actual plot itself uses the poly() command to produce a set of numbers from a linear or quadratic function according to the user input (that is, input$graph). Note the use of as.numeric() to coerce the value we get from the radio button definition in index.html from a string to a number.

This is a common source of errors when using Shiny code, and you must remember to keep track of how variables are stored, whether as lists, strings, or other variable types, and either coerce them in place (as done here), or coerce them all in one go using a reactive function.

The latter option can be a good idea to make your code less fiddly and buggy because it removes the need to keep track of variable types in every single function you write. There is more about defining your own reactive functions and passing data around a Shiny instance in the next chapter. The type ="l" argument returns a line graph, and the xlab and ylab arguments give labels to the x and y axes.

The following screenshot shows the finished article:

Finished article
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset