<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/master-r-shiny-one-trick-to-build-maintainable-and-scalable-event-chains/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.statworx.com/de/blog/master-r-shiny-one-trick-to-build-maintainable-and-scalable-event-chains/"> r-bloggers – STATWORX</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Introduction</h2>
<p>Writing appealing interactive web applications – one of <a rel="nofollow" href="https://www.statworx.com/" target="_blank">STATWORX's</a> many competences – is an ease with R shiny. Just a few lines of code in one R script create the whole logic you need to let the whole magic of shiny happen. It is so simple that you can make a hello world app in a heartbeat, like so.</p>
<pre><code>library(shiny)
ui &lt;- fluidPage(
  &quot;Hello, World!&quot;
)
server &lt;- function(input, output, session) { }
shinyApp(ui, server)
</code></pre>
<p>Today I am going to show you one way you can use native shiny syntax to modularize pieces of your code in a way that makes your code basis easily maintainable and extendable. Since I assume you are already familiar with shiny, I’ll skip the intro wading pool example and go right to the high-dive.</p>
<h2>What are event chains?</h2>
<p>An event chain describes the relationship between events and tasks and how the events affect each other. In some cases, you may want to have an app that takes user input and performs actions based on the nature of the input, potentially asking for more information along the way. In such a case, chances are you want to implement an event chain. You could immediately start hacking some crude solution to your problem, but you may risk creating hardly comprehensible code. Furthermore, imagine that requirements on your event chain suddenly change. In this case, it is important to modularize your event chain so that it remains maintainable and adaptable.</p>
<h2>Example: the friend logger</h2>
<p>So, let me illustrate how to build a modularized event chain. Imagine you are pedantic about time and take appointments seriously. Quite to the detriment of your so called &quot;friends&quot;, you make no exceptions. Every time a friend is too late, you suffer so bad you have decided to use a shiny app to keep score of your friends' visits in order to determine how reliable they are (you pathetic you!). Requirements on the app's usage are simple, as shown in the graph below. </p>
<p><img src="https://i1.wp.com/www.statworx.com/wp-content/uploads/friends.png?resize=395%2C477&ssl=1" alt="friends" width="395" class="wp-image-15782" data-recalc-dims="1" height="477"></p>
<p>You want to compare the expected arrival time of your friend with his actual arrival time. If his delay is above a certain threshold (e.g. 5 minutes), you want to protocol his excuse for being late. If you deem his excuse as being acceptable, you neglect his sin (but still keep protocol!). If he is punctual, he receives a bonus point. If he arrives too late and his excuse is not acceptable, he receives a minus point. In any case, you log his visit (how low can you get?). To keep things more visual, here is a sketch of the app's UI including the event sequence when a friend is being late.</p>
<p><img alt="friends-app-view" src="https://i1.wp.com/www.statworx.com/wp-content/uploads/friends-app-view.png?w=450&ssl=1" class="wp-image-15776" data-recalc-dims="1"></p>
<p>Now, it is time to implement the app.</p>
<h2>Event chain architecture in R Shiny</h2>
<p>It takes two ingredients to implement event chains:</p>
<ol>
<li>triggers that are stored in <code>reactiveValues()</code></li>
<li>observers (<code>observeEvent()</code>) that are triggered and carry out the actual checks and other computations </li>
</ol>
<p>The actual trick is to find the appropriate number of <code>observeEvent()</code>s so that each step in the event chain is covered by one <code>observeEvent</code> and therefore no code redundancies are created. Using the example above, we have three possible sequences of events:</p>
<ol>
<li>Friend is too late and has a good excuse</li>
<li>Friend is too late and doesn't have a good excuse</li>
<li>Friend is not too late</li>
</ol>
<p>In all three cases, we need to log a friend's visit, so it definitely makes sense to put the visit logging part in <strong>one</strong> <code>observeEvent</code> and to call that observer at the end of each of the sequences above. Drawing an event chain diagram comes in especially handy here, as it supports a suitable architectural design choice. I used <a rel="nofollow" href="https://www.draw.io/" target="_blank">draw.io</a> for the task.</p>
<p>For the app, I used one <code>reactiveValues</code>-object in which I put all triggers (you can find the whole app code on <a rel="nofollow" href="https://github.com/STATWORX/blog/tree/master/shiny_friend_scorer" target="_blank">GitHub</a>).</p>
<pre><code>shinyServer(function(input, output, session) {
  
  # Data
  rv &lt;- reactiveValues(
    ...
    # Triggers
    ask_for_reason = TRUE,
    change_friend_score = TRUE,
    save_visit = TRUE,
    error = FALSE
  )
  ...
})
</code></pre>
<p>I use boolean values for the triggers so that I only have to negate them if I want to change their value (<code>a &lt;- !a</code>). Using integers would also work, but I find the flip-trick nicer. Let's look at the part of the chain where a friend's punctuality is checked in more detail. The module that checks punctuality also reads in the data. Depending on the input, it either calls the &quot;Ask-for-a-reason&quot;-module or directly calls the visit logger.</p>
<pre><code># Submit friend data ----
observeEvent(input$submit, {
  # Collect data
  ...
    
  is_delayed &lt;- difftime(actual_time, expected_time, units = &quot;mins&quot;) > input$acceptance
  if (is_delayed) {
    # Friend is delayed --> trigger Ask-for-reason-module
    rv$ask_for_reason &lt;- isolate(!rv$ask_for_reason)
    return()
  }
  # Friend seems punctual --> Add a point to score list :)
  friend_data &lt;- set_data(friend_data, score = 1) 
  # Trigger visit logger
  rv$change_friend_score &lt;- isolate(!rv$change_friend_score)
})
</code></pre>
<p>As you can see, once you have drawn the event chain it is quite intuitive to translate it into shiny code. If the friend is punctual, we set his score to one (<code>score</code> will be added in the visit logger module) and call the visit logger module, which looks like this:</p>
<pre><code># Change friend score ----
observeEvent(rv$change_friend_score, ignoreInit = TRUE, {
  rv$friend_score[friend_score$name == friend_data$name, &quot;score&quot;] &lt;-
    isolate(rv$friend_score[friend_score$name == friend_data$name, &quot;score&quot;]) + 
    friend_data$score
  # Make change permanent
  saveRDS(rv$friend_score, &quot;data/friend_score.RDS&quot;)
  rv$save_visit &lt;- isolate(!rv$save_visit)
 })
</code></pre>
<p>Note that the <code>rv$save_visit</code> trigger simply calls an observer that adds another row to the friend visit table and does some cleaning.</p>
<p>So now let's make a little test run with the ready product. For your app to work, you of course have to first create an initial dataset with your friends and their initial scores in order to know who you are keeping record of. In the example below, we have four friends: John, Emily, Olivia, and Ethan. You can see their scores in the lower left corner. Past visits are logged and displayed in the upper right corner.</p>
<p><img alt="app-ui" src="https://i0.wp.com/www.statworx.com/wp-content/uploads/app-ui.png?w=450&ssl=1" class="wp-image-15767" data-recalc-dims="1"></p>
<p>John wants to hang out with us to play some brutal video games, and for no obvious reason we made an appointment at 9 am. However, John shows up 7 (!!!) minutes late. Enough is enough. We enter his misdeed.</p>
<p><img alt="john-entered" src="https://i1.wp.com/www.statworx.com/wp-content/uploads/john-entered.png?w=450&ssl=1" class="wp-image-15785" data-recalc-dims="1"></p>
<p>It exceeds the threshold, so we are, as expected, prompted to enter the reason.</p>
<p><img alt="enter-reason" src="https://i2.wp.com/www.statworx.com/wp-content/uploads/enter-reason.png?w=450&ssl=1" class="wp-image-15770" data-recalc-dims="1"></p>
<p>When we asked John to justify himself, he just shrugged his shoulders. How dare he?! That's a minus point… </p>
<h2>Extend our event chain</h2>
<p>Even though you hurt all over because of John's unreliability, you are quite happy with your app. Yet, things could be better! For example, every time you misspell a friend in the name field when protocolling a visit, the app crashes. Your app could use some (additional) sanity checks. A perfect use case for showing the flexibility of your architecture. After a few months of deep reflection, you came up with a new event flow graph that takes care of wrong inputs.</p>
<p><img src="https://i1.wp.com/www.statworx.com/wp-content/uploads/friends-with-error.png?resize=395%2C537&ssl=1" alt="friends-with-error" width="395" class="wp-image-15779" data-recalc-dims="1" height="537"></p>
<p>You figured two spots where the app ought to be stabilized. First, you want to throw an error to the user if a friend doesn't exist (without stopping the app). Second, you require yourself to enter a reason (we all know how sloppy our future self can be from time to time).</p>
<p>With the already chosen modularized structure, it is easy to incorporate these checks. You simply need to add one more trigger (<code>rv$error</code>) and one global container that stores the error information.</p>
<pre><code># Error handler
error &lt;- reactiveValues(
  title = &quot;&quot;,
  message = &quot;&quot;
)
</code></pre>
<p>If you for example want to check whether an entered name exists in your data base, all you have to do is to add a few lines of code at the beginning of the observer where a friend's punctuality is checked.</p>
<pre><code># Submit friend data ----
observeEvent(input$submit, {
  # Friend exists?
  if (!input$name %in% rv$friend_score$name) {
    error$title &lt;- &quot;%s not found&quot; %>% sprintf(., input$name)
    error$message &lt;- h1(&quot;404&quot;)
    rv$error &lt;- isolate(!rv$error)
    return()
  }
  ...
})
</code></pre>
<p>If the name doesn't match any of your friends' names, you trigger an error handler module whose only purpose is to show an error message:</p>
<pre><code># Error handling ----
observeEvent(rv$error, ignoreInit = TRUE, {
  showModal(modalDialog(    
    title = error$title,
    error$message,
    footer = actionButton(&quot;exit&quot;, &quot;Ok&quot;, class = &quot;btn-primary&quot;)
  ))
})
</code></pre>
<p>The nice thing is that you can use this module to handle any errors, no matter which sanity checks have caused them. </p>
<p>So if we go back to the app now and enter a name that doesn't exist (like Tobias), we get the following error message:</p>
<p><img alt="friend-not-found" src="https://i1.wp.com/www.statworx.com/wp-content/uploads/friend-not-found.png?w=450&ssl=1" class="wp-image-15773" data-recalc-dims="1"></p>
<p>Furthermore, if we miss to enter a reason when being asked for one, we get a passive aggressive reminder:</p>
<p><img alt="no-reason-give" src="https://i2.wp.com/www.statworx.com/wp-content/uploads/no-reason-give.png?w=450&ssl=1" class="wp-image-15788" data-recalc-dims="1"></p>
<p>You are welcome! So would you excuse me now? I have some visits to protocol…</p>
<div>
<h6>Über den Autor</h6>
<p><img src="https://i1.wp.com/www.statworx.com/wp-content/uploads/tobias-2-300x300.jpg?resize=180%2C180&ssl=1" width="180" alt="Tobias Krabel" class="wp-user-avatar wp-user-avatar-180" data-recalc-dims="1" height="180"></p>
<div>
<h4>Tobias Krabel</h4>
<p>Tobias ist im Data Science Team und absolviert im Moment seinen 2. Master in Informatik. In seiner Freizeit ist er sozial engagiert und geht gerne Wandern in der Natur.</p>
</div>
</div>
<p>Der Beitrag <a rel="nofollow" href="https://www.statworx.com/de/blog/master-r-shiny-one-trick-to-build-maintainable-and-scalable-event-chains/" target="_blank">Master R shiny: One trick to build maintainable and scalable event chains</a> erschien zuerst auf <a rel="nofollow" href="https://www.statworx.com/de/" target="_blank">STATWORX</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="https://www.statworx.com/de/blog/master-r-shiny-one-trick-to-build-maintainable-and-scalable-event-chains/"> r-bloggers – STATWORX</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/b7i-a_wezVA" height="1"></a></div>