<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/source-and-list-organizing-r-shiny-apps/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-bar.net/organize-r-shiny-list-source/"> R – R-BAR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Keeping R Shiny code organized can be a challenge. One method to organize your Shiny UI and Server code is to use a combination of R’s list and source functions. Another method to organize you’re Shiny code is through <a rel="nofollow" href="https://shiny.rstudio.com/articles/modules.html" title="Modularizing Shiny app code" target="_blank">modularization techniques</a>. Here though, we’re going concentrate on the list and source options.</p>
<p>If you feel comfortable with Shiny and want to get strait to the answer, check out the <a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#Solution_Use_list_with_source" target="_blank">Solution</a> section. Otherwise, read on!</p>
<h2>Outline</h2>
<ol>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#Difficulty_Organizing_Shiny_UIs" target="_blank">Difficulty Organizing Shiny UIs</a>
<ol>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#UI_Source_Example_That_Doesnt_Always_Work" target="_blank">A UI Source Example That Usually Doesn’t Work</a></li>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#When_Source_Fails_in_the_UI" target="_blank">When Source Fails in the UI</a></li>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#Solution_Use_list_with_source" target="_blank">Solution</a></li>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#usage_note" target="_blank">Usage Note</a></li>
</ol>
</li>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#Organizing_the_Shiny_Server_with_Source" target="_blank">Organizing the Shiny Server with Source</a></li>
<li><a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/#Summary" target="_blank">Summary</a></li>
</ol>
<h1>Difficulty Organizing Shiny UIs</h1>
<p>If you have a Shiny application with a lot of controls, it’s easy to get lost in the braces, parentheses and brackets. Using R’s list() and source() functions, we can make UI code much more manageable by moving components out to other files.</p>
<blockquote>
<p>So how do you do it?</p>
</blockquote>
<p>To get us started, we are going to work with the starter app provided in R studio. Click File →New →Shiny Web App… . A dialogue box will pop up. My setup details are shown below in the R-Studio dialogue box. Choose a working directory appropriate for you and press Create.</p>
<p><img alt="New Shiny App Dialogue Box" src="https://i0.wp.com/cdn.r-bar.net/PID511/New-Shiny-App.jpg?w=456" data-recalc-dims="1"></p>
<p>R-Studio will then show the code for the starter Shiny App. The demo code has 4 parts.</p>
<ul>
<li>Load the Shiny Library</li>
<li>Define the UI</li>
<li>Define the Server</li>
<li>Run the app.</li>
</ul>
<p>We are going to start on the UI portion of the Shiny app shown in the screen capture below. This particular UI can be broken down into two parts the “Side Bar Panel” [lines 9-13] and the “Main Panel” [lines 15-17]. What we are going to do is factor out the content in the Side Bar Panel to a file named Side_Panel_CTRL.R and the Main Panel content to a file named Main_Panel_OUTPUT.R.</p>
<p><img alt="UI Section of Shiny Starter Application" src="https://i2.wp.com/cdn.r-bar.net/PID511/Starter-Shiny-UI.gif?w=456" data-recalc-dims="1"></p>
<p>So, make the two new R scripts named Side_Panel_CTRL.R and Main_Panel_OUTPUT.R. From the app.R file, <strong>MOVE</strong> the sliderInput (lines 10-12 above) to the Side_Panel_Control.R file and the plotOutput (line 16) to the Main_Panel_OUTPUT.R. Make sure these two new files are saved in the same folder as your app.R file.</p>
<h2>A UI Source Example that Usually Doesn’t Work</h2>
<p>Once you have your files setup, add the source() statements into you app.R file as shown in the code snippet below (lines 8 &amp; 12).</p>
<div><table><tr><td><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td><pre><span># Define UI for application that draws a histogram</span>
ui <span>&lt;-</span> fluidPage<span>(</span>
   titlePanel<span>(</span><span>&quot;List and Source UI&quot;</span><span>)</span>, <span># Title Page</span>
 
   <span># Sidebar with a slider input for number of bins</span>
   sidebarLayout<span>(</span>  
      sidebarPanel<span>(</span> <span># The Side Bar</span>
        <span>source</span><span>(</span><span>file</span> <span>=</span> <span>&quot;Side_Panel_CTRL.R&quot;</span>, <span>local</span> <span>=</span> <span>T</span><span>)</span>
      <span>)</span>,
   <span># Show a plot of the generated distribution </span>
   mainPanel<span>(</span> 
        <span>source</span><span>(</span><span>file</span><span>=</span><span>&quot;Main_Panel_OUTPUT.R&quot;</span>, <span>local</span><span>=</span><span>T</span><span>)</span>
      <span>)</span>
   <span>)</span>
<span>)</span></pre></td></tr></table></div>
<p>Great your files are setup.</p>
<p>Press the Run App Button in R Studio and the app starts as you might expect. You’ll notice that the word <strong>TRUE</strong> pops up at the bottom of the slider control and the plot. Not sure why this happens, but you can remove it by adding “[1]” to the end of the source() statement as shown in the screen capture below summarizing where we are right now.</p>
<p><img alt="UI Section of Shiny Starter Application - Source Only" src="https://i1.wp.com/cdn.r-bar.net/PID511/Shiny-UI-Source-1.gif?w=456" data-recalc-dims="1"></p>
<p>Cool, but this is about as far as you’re going to get with source command alone.</p>
<h2>When Source Fails in the UI</h2>
<p>The source command alone can fail in the UI sections of a Shiny app. To demonstrate, we are going to add just <strong>one</strong> additional control to our side panel control file. First, though, let me show you that adding one additional control works when I add it directly to the app.R file in the UI section:</p>
<p><img alt="UI Section of Shiny Starter Application. Two controls in app." src="https://i0.wp.com/cdn.r-bar.net/PID511/Working-Shiny-Two-Controls.gif?w=456" data-recalc-dims="1"></p>
<p>To the right of the code, you can see that the app works. Now let’s see what happens when we <strong>move</strong> the following control code back to the Side_panel_CTRL.r file.</p>
<div><table><tr><td><pre>1
2
3
4
5
6
7
</pre></td><td><pre><span>#Slider Input</span>
  <span>#Slider Control</span>
  sliderInput<span>(</span><span>&quot;bins&quot;</span>, <span>&quot;Number of bins:&quot;</span>,
              <span>min</span> <span>=</span> <span>1</span>, <span>max</span> <span>=</span> <span>50</span>, value <span>=</span> <span>30</span>
  <span>)</span>, 
  <span>#text box control</span>
  textInput<span>(</span><span>&quot;textBox1&quot;</span>, label <span>=</span> <span>&quot;Enter Value&quot;</span><span>)</span></pre></td></tr></table></div>
<p>OK, moved the code. Here is what the three files should look like and the result of trying to run them.</p>
<p><img alt="UI Section of Shiny Starter Application - source Causing error with two controls." src="https://i0.wp.com/cdn.r-bar.net/PID511/Shiny-UI-With-Source-Error.gif?w=456" data-recalc-dims="1"></p>
<p>hmm… We had an error, and it seems to involve the syntax of the code we are sourcing… perhaps the comma. How do we fix this?</p>
<h2>Solution</h2>
<p>The simple fix is to wrap the code in your UI files with the list command as shown in the following few screen shots: Look specifically at lines 1 and 9 of the Side_Panel_CTRL.r file and 1 and 5 of Main_Panel_OUTPUT.r file.</p>
<p><img alt="UI Section of Shiny Starter Application - Source list solution." src="https://i1.wp.com/cdn.r-bar.net/PID511/Working-Shiny-Two-Controls-Sourced.gif?w=456" data-recalc-dims="1"></p>
<h2>Usage Note</h2>
<p>I find the source() and list() combo to be particularly useful when I work with tabbed panels. A quick example is shown below with some tabPanel code on lines 11-12. The controls for these two panels are coded in the source files as described previously.</p>
<p><img alt="Shiny UI tabPanel source list combo example." src="https://i2.wp.com/cdn.r-bar.net/PID511/Source-List-TabPanel-Example.gif?w=456" data-recalc-dims="1"></p>
<h1>Organizing the Shiny Server with Source</h1>
<p>Server side Shiny is good old fashioned R-code and can be easily sourced from an external file using the source() command without list.</p>
<blockquote>
<p>source(<br>
file = “[source file path]”,<br>
local = True #<br>
)</p>
</blockquote>
<p>The only trick with server side Shiny is dealing with the reactive elements like “reactive({…})”. For these you need to put the source() command in place of the “…”. To illustrate consider the following two code snippets.</p>
<p>Out-of-the-box sever code looks something like this:</p>
<div><table><tr><td><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td><pre><span># Define server logic required to draw a histogram</span>
server <span>&lt;-</span> <span>function</span><span>(</span>input, output<span>)</span> <span>{</span>
   output$distPlot <span>&lt;-</span> renderPlot<span>(</span><span>{</span>
     <span># generate bins based on input$bins from ui.R</span>
     x    <span>&lt;-</span> <span>faithful</span><span>[</span>, <span>2</span><span>]</span> 
     bins <span>&lt;-</span> <span>seq</span><span>(</span><span>min</span><span>(</span>x<span>)</span>, <span>max</span><span>(</span>x<span>)</span>, length.<span>out</span> <span>=</span> input$bins <span>+</span> <span>1</span><span>)</span>
     <span># draw the histogram with the specified number of bins</span>
     <span>hist</span><span>(</span>x, breaks <span>=</span> bins, <span>col</span> <span>=</span> <span>'darkgray'</span>, border <span>=</span> <span>'white'</span><span>)</span>
   <span>}</span><span>)</span>
<span>}</span></pre></td></tr></table></div>
<p>If you source out lines 3 through 9 after the output$distPlot assignment to a file called Server_Plot.R, and leave the server code like this:</p>
<div><table><tr><td><pre>1
2
3
4
</pre></td><td><pre>server <span>&lt;-</span> <span>function</span><span>(</span>input, output<span>)</span> <span>{</span>
   output$distPlot <span>&lt;-</span> <span>source</span><span>(</span><span>file</span><span>=</span><span>&quot;Server_Plot.R&quot;</span>, <span>local</span><span>=</span><span>T</span><span>)</span> 
 
<span>}</span></pre></td></tr></table></div>
<p>You’ll get an error:</p>
<blockquote>
<p>“Error in .subset2(x, “impl”)$defineOutput(name, value, label) :<br>
Unexpected list output for distPlot”</p>
</blockquote>
<p>To avoid this error, keep the renderPlot({}) reactive element in the app.R file and source from within like so:</p>
<div><table><tr><td><pre>1
2
3
4
5
</pre></td><td><pre>server <span>&lt;-</span> <span>function</span><span>(</span>input, output<span>)</span> <span>{</span>
   output$distPlot <span>&lt;-</span> renderPlot<span>(</span><span>{</span>
     <span>source</span><span>(</span><span>file</span><span>=</span><span>&quot;Server_Plot.R&quot;</span>, <span>local</span><span>=</span><span>T</span><span>)</span> 
   <span>}</span><span>)</span>
<span>}</span></pre></td></tr></table></div>
<p>For the server side, that’s it. You should also notice that compared to the UI side, we did not need to place the “[1]” at the end of the source command.</p>
<h1>Summary</h1>
<p>Shiny is a great tool for communicating data, but its easy to get lost in the braces, brackets, and parentheses. To help simplify your next Shiny application, try using the source-list combo and don’t forget the “[1]” at the end of the source statement, or you’ll have a while bunch of TRUEs running around. On the server side, we need to be careful around reactive elements.</p>
<p>The post <a rel="nofollow" href="http://r-bar.net/organize-r-shiny-list-source/" target="_blank">Source and List: Organizing R Shiny Apps</a> appeared first on <a rel="nofollow" href="http://r-bar.net/" target="_blank">R-BAR</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-bar.net/organize-r-shiny-list-source/"> R – R-BAR</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/fVgCzxVsCYM" height="1"></a></div>