Single-file application

Single-file apps have UI and server code in the same file. For such a coding style, the app skeleton can be given as follows:

ui<-function(request){# UI code } 
server<- function(input,output,session){# Server Code}
shinyApp(ui,server,enableBookmarking="url")

We can see that the UI code is returned as a function rather than fluidpage or any other UI element. And in the last line of code, the enableBookmarking argument is set to "url". The rest of the code is similar to Shiny apps. Let's develop an app with the preceding skeleton that finds the square of a number. Starting with UI, there is a textInput() box for getting the input, verbatimTextOutput() for showing output, and bookmarkButton() for bookmarking:

 ui<-function(request){ 
fluidPage( 
    textInput("inptxt","Enter Number"), 
    verbatimTextOutput("outsquare"), 
    bookmarkButton())  
}     

In the server code, we have to calculate the square of the inputted number and send it for display. We can see in the following code that renderText() is first converting the inputted text into a number and then calculating the square:

server<- function(input,output,session){ 
  output$outsquare<- renderText({ 
    (as.numeric(input$inptxt)*as.numeric(input$inptxt)) 
})  }   

In the last, we have to call shinyApp() in which we are passing the enableBookmarking argument as "url":

shinyApp(ui,server,enableBookmarking="url")   

Let's have a look at output of the code:

We can see that in the app, the input is 2 and the output value is 4. The bookmark window shows the linked URL with some values that are encoding the input/output, http://127.0.0.1:4255/?_inputs_&inptxt=%222%22.

Single file Shiny applications can also be returned by a function. Let's recreate the square application using function:

App<-function(){ 
ui<-function(request){ 
  fluidPage( 
    textInput("inptxt","Enter Number"), 
    verbatimTextOutput("outsquare"), 
    bookmarkButton() 
   )  
  } 
server<- function(input,output,session){ 
  output$outsquare<- renderText({ 
    (as.numeric(input$inptxt)*as.numeric(input$inptxt)) 
  }) 
} 
shinyApp(ui,server,enableBookmarking="url") 
} 

To run the app, copy the code in to an R Script file, select all code, and run it. After that, we can execute the code using App() in console or R Script. enableBookmark() can also be set at the beginning of the app code.

Now, we are ready to develop our application for multiple files.

..................Content has been hidden....................

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