<p>In this tutorials sequence, we are going to see three tricks to do the following in a Shiny app:</p>
<ol>
<li><a target="_blank" rel="nofollow" href="https://antoineguillot.wordpress.com/2017/02/15/three-r-shiny-tricks-to-make-your-shiny-app-shines-13/">Add Next and Previous buttons to navigate in a tabBox</a></li>
<li><a target="_blank" rel="nofollow" href="https://antoineguillot.wordpress.com/2017/02/21/three-r-shiny-tricks-to-make-your-shiny-app-shines-23-semi-collapsible-sidebar/">Build a non completely collapsible sidebar to keep the icon visible on collapse</a></li>
<li>Add button on a datatable output to delete/modify/ do an action on a given row.</li>
</ol>
<p>Today, we are going to see how to add buttons in each rows of a datatable to delete, edit or compare it with other rows.<br>
The app is live <a target="_blank" rel="nofollow" href="https://www.enhancedata.tech/ButtonDataTable/">here</a>.</p>
<h3>3. Buttons to delete, edit and compare Datatable rows</h3>
<p>Here is what we want to achieve:</p>
<figure data-shortcode="caption" class="wp-caption"><img data-image-description="" data-orig-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/02/exemplebuttondt.gif?w=456&amp;ssl=1" data-orig-size="1824,854" data-image-title="exemplebuttondt" class="wp-image-1201" data-comments-opened="1" data-recalc-dims="1" data-attachment-id="1201" data-permalink="https://antoineguillot.wordpress.com/2017/03/01/three-r-shiny-tricks-to-make-your-shiny-app-shines-33-buttons-to-delete-edit-and-compare-datatable-rows/exemplebuttondt/" alt="ExempleButtonDT.gif" data-medium-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/02/exemplebuttondt.gif?w=456&amp;ssl=1?w=300" data-large-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/02/exemplebuttondt.gif?w=456&amp;ssl=1?w=616" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/02/exemplebuttondt.gif?w=456&ssl=1"><br>
<figcaption class="wp-caption-text">The final application</figcaption>
</figure>
<p>As you can seen, the final application offer a lot of functionalities, like selecting row with checkboxes, comparing, deleting them and also modifying them.<br>
Even though you can select the rows via the classical datatable functions, checkboxes make it more visual for the users (he knows there is something it can do). In addition to this, the button are a clear call to action so that the users do not have to serach how to do the different actions.</p>
<h4>a.It all begins with a data.table (or a datatable)</h4>
<p>To begin with, we will only display a classic data.table, generate some fake datas in our app.</p>
<p><em>ui.R</em></p>
<pre>
library(shiny)
library(shinydashboard)

dashboardPage(dashboardHeader(disable = T),
 dashboardSidebar(disable = T),
 dashboardBody(uiOutput(&quot;MainBody&quot;)
 )
 )
 </pre>
<p>The ui is very classic, since most of the content is dynamic, we will generate the page and elements in the server.</p>
<p><em>server.R</em></p>
<pre>
library(shinydashboard)
library(data.table)
library(DT)

shinyServer(function(input, output) {

###Creating reactive values since we will need to modify the table with events and triggers
 vals=reactiveValues()
 vals$Data=data.table(
 Brands=paste0(&quot;Brand&quot;,1:10),
 Forecasted_Growth=sample(1:20,10),
 Last_Year_Purchase=round(rnorm(10,1000,1000)^2),
 Contact=paste0(&quot;Brand&quot;,1:10,&quot;@email.com&quot;)
 )

##The Body is classic, we just used the group button to improve the render
##And to show the user the actions are related
 output$MainBody=renderUI({
   fluidPage(
    box(width=12,
     h3(strong(&quot;Actions on datatable with buttons&quot;),align=&quot;center&quot;),
     hr(),
     column(6,offset = 6,
##Grouped button
       HTML('') ), 
##Rendering the datatable 
column(12,dataTableOutput(&quot;Main_table&quot;)) }) 
##The code may seem weird but we will modify it later 
output$Main_table=renderDataTable({ DT=vals$Data datatable(DT)} )

 </pre>
<p><strong>Data generation:</strong> The apps create fakes yearly sales data for 10 brands, with a name, an email and a fake estimated growth. The data is purely cosmetic.</p>
<p><strong>Main Body: </strong>The body contains a title, three buttons which are grouped using the html div btn-group. When Shiny generates the html code, the div will encapsulate the action buttons which will be showed as grouped.</p>
<p><strong>Storing the table in a reactive value:</strong> Since we will want to perform action on the data with buttons and eventObserver the modifications of the data will be done with side effects. Hence reactiveValues are a must.</p>
<h4>b. On which we added some buttons</h4>
<p>Now, lets add the buttons to our datatable. Basically, they will be added through html code and the datatble will be asked not to escape strings.</p>
<p> </p>
<pre>
 output$Main_table=renderDataTable({
DT=vals$Data
DT[[&quot;Select&quot;]]&lt;-paste0('&lt;input type=&quot;checkbox&quot; name=&quot;row_selected&quot; value=&quot;Row',1:nrow(vals$Data),'&quot;>
')

DT[[&quot;Actions&quot;]]&lt;-
paste0('
&lt;div class=&quot;btn-group&quot; role=&quot;group&quot; aria-label=&quot;Basic example&quot;>
&lt;button type=&quot;button&quot; class=&quot;btn btn-secondary delete&quot; id=delete_',1:nrow(vals$Data),'>Delete&lt;/button>
&lt;button type=&quot;button&quot; class=&quot;btn btn-secondary modify&quot;id=modify_',1:nrow(vals$Data),'>Modify&lt;/button>
&lt;/div>
')
datatable(DT,
escape=F)}
)

 </pre>
<p><strong>Checkboxes: </strong>The checkboxes will be used to select the rows on which the user want to perform some actions (Deletion, comparison). Since they all have the same name it will be easy to access their value through JS. We will get the value of the row by deleting the ‘Row_’ from the checkbox value.</p>
<p><strong>Actions Buttons: </strong>Each row will contain a group of two buttons, one to delete the row and the other one to modify it. Again, the app will access the row to delete and the action to do through the button ID.</p>
<p><strong>Escape: </strong>Perhaps you noticed the <em>escape=F </em>option, by using it, datatable will render the buttons according to their HTML codes instead of strings.</p>
<h4><strong>c. But these buttons were doing nothing.</strong></h4>
<p>No matter you click on the buttons or not, nothing will happen. They need to be linked with the Shiny App. First, let’s link the new row button.</p>
<p>We will just add an event observer in the server which will add a new row to vals$Data</p>
<pre>
observeEvent(input$Add_row_head,{
 new_row=data.frame(
 Brands=&quot;NewBrand&quot;,
 Forecasted_Growth=sample(1:20,1),
 Last_Year_Purchase=round(rnorm(1,1000,1000)^2),
 Contact=&quot;NewBrand@email.com&quot;)
 vals$Data=rbind(vals$Data,new_row)
 })

 </pre>
<p> </p>
<p>The observer is just generating a new row and appending it to vals$Data.</p>
<h4><strong>d. Getting the selected row/ticked box in Shiny.</strong></h4>
<p>Now, to be able to compare the selected row and to delete them, we need to create a new Shiny input with the list of selected checkbox.</p>
<p>This can be done adding a js script at the end of output$MainBody</p>
<pre>

 tags$script(HTML('$(document).on(&quot;click&quot;, &quot;input&quot;, function () {
var checkboxes = document.getElementsByName(&quot;row_selected&quot;);
var checkboxesChecked = [];
for (var i=0; i&lt;checkboxes.length; i++) {

if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i].value);
}
}
Shiny.onInputChange(&quot;checked_rows&quot;,checkboxesChecked);
})'))

 </pre>
<p><strong>Line by line:<br>
</strong>First we are adding a new script, the HTML() is used to avoid escaping, which may lead to some weird stuff with the ‘>’.<br>
Then when the user is clicking on an input, the script runs a function.<br>
We are storing all the checkboxes and we create an empty arrow that will be filled with the id of ticked checkbox.<br>
The last line is assigning the id of checked boxes to input$checked rows.</p>
<h4><strong>e. Now, let’s delete and compare rows</strong></h4>
<p>Now, the app can access the list of checked rows. Let’s delete these ones through an observe event (to be added in the shinyServer function)</p>
<pre>

observeEvent(input$Del_row_head,{
 row_to_del=as.numeric(gsub(&quot;Row&quot;,&quot;&quot;,input$checked_rows))
 vals$Data=vals$Data[-row_to_del]}
 )

 </pre>
<p>Nothing fancy in it, the value of rows to delete is gotten by deleting the <em>“Row”</em> part of the input. Then, the value <em>of vals$Data</em> is updated.<br>
To compare the rows, the code is similar.</p>
<pre>
observeEvent(input$Compare_row_head,
  {
   row_to_del=as.numeric(gsub(&quot;Row&quot;,&quot;&quot;,input$checked_rows))
   number_brands=length(row_to_del)
   vals$fake_sales=data.table(
       month=rep(1:12,number_brands),
       sales=round(rnorm(12*number_brands,1000,1000)^2)/12,
       Brands=rep(vals$Data[row_to_del,Brands],each=12)
      )
 vals$fake_sales[,Brands:=as.factor(Brands)]
 showModal(fake_sales_modal)
 }
 )

 </pre>
<p>As previously, the observer get the selected rows, then some fakes data are generated and the modal containing the plot is shown. The modal is generate using the code below:</p>
<pre>

 fake_sales_modal=modalDialog(
fluidPage(
h3(strong(&quot;Monthly sales of selected brands&quot;),align=&quot;center&quot;),
plotOutput('sales_plot')
),
size=&quot;l&quot;
)

output$sales_plot=renderPlot({
require(ggplot2)
ggplot(vals$fake_sales,aes(x=month,y=sales,color=Brands))+geom_line()
})
 </pre>
<p>The plot needs to be outside of the modal since it is dependent on vals$fake_sales which is reactive.</p>
<p>Now when you click on the compare or delete selected rows, the actions should happen correctly.</p>
<h4>f. Inrow button deletion.</h4>
<p>Now, let’s focus on deleting a row with the inrow button. As previously, we first need to link the button with a Shiny Input, this will be done through a small JS script  to add at the end of output$MainBody</p>
<pre>
tags$script(&quot;$(document).on('click', '#Main_table button', function () {
 Shiny.onInputChange('lastClickId',this.id);
 Shiny.onInputChange('lastClick', Math.random())
 });&quot;)
 </pre>
<p>When a button in <em>output$Main_Table</em> is clicked, <em>input$lastClickId</em> got assigned the id of this button and <em>input$lastClick</em>  got assigned a random value.<br>
The last click is used to detect the click (for instance when a button is clicked twice, the id won’t change and hence cannot be observed).<br>
The app will observe <em>input$lastClick</em>:</p>
<pre>
observeEvent(input$lastClick,
 {
 if (input$lastClickId%like%&quot;delete&quot;)
 {
 row_to_del=as.numeric(gsub(&quot;delete_&quot;,&quot;&quot;,input$lastClickId))
 vals$Data=vals$Data[-row_to_del]
 }
 else if (input$lastClickId%like%&quot;modify&quot;)
 {
 showModal(modal_modify)
 }
 }
 )
 </pre>
<p>Below is the structure of the modal, it is basically a page with a data.table and an action button to trigger the save of the modification.</p>
<pre>
 modal_modify=modalDialog(
fluidPage(
h3(strong(&quot;Row modification&quot;),align=&quot;center&quot;),
hr(),
dataTableOutput('row_modif'),
actionButton(&quot;save_changes&quot;,&quot;Save changes&quot;),

),
size=&quot;l&quot;
)
 </pre>
<p>The process to delete the row is the same as with checkbox selection. We are only keeping the end of the id which contains the number of the row to delete.</p>
<h4><strong>g.One modal to modify them all.</strong></h4>
<p>Now, we want to be able to modify a given line of the data.table. To do see, we will pop a modal with text field when the user click on the modify button.</p>
<figure data-shortcode="caption" class="wp-caption"><img data-image-description="" data-orig-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/03/modifymodalshiny.gif?w=456&amp;ssl=1" data-orig-size="1006,368" data-image-title="modifymodalshiny" data-comments-opened="1" class="wp-image-1319" data-recalc-dims="1" data-attachment-id="1319" data-permalink="https://antoineguillot.wordpress.com/2017/03/01/three-r-shiny-tricks-to-make-your-shiny-app-shines-33-buttons-to-delete-edit-and-compare-datatable-rows/modifymodalshiny/" alt="ModifyModalShiny.gif" data-medium-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/03/modifymodalshiny.gif?w=456&amp;ssl=1?w=300" data-large-file="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/03/modifymodalshiny.gif?w=456&amp;ssl=1?w=616" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://i1.wp.com/antoineguillot.files.wordpress.com/2017/03/modifymodalshiny.gif?w=456&ssl=1"><br>
<figcaption class="wp-caption-text">The modal to modify a row</figcaption>
</figure>
<p>The datatable inside has the following structure:</p>
<pre>
output$row_modif&lt;-renderDataTable({
selected_row=as.numeric(gsub(&quot;modify_&quot;,&quot;&quot;,input$lastClickId))
old_row=vals$Data[selected_row]
row_change=list()
for (i in colnames(old_row))
{
if (is.numeric(vals$Data[[i]]))
{
row_change[[i]]&lt;-paste0('&lt;input class=&quot;new_input&quot; type=&quot;number&quot; id=new_',i,'>
')
}
else
row_change[[i]]&lt;-paste0('&lt;input class=&quot;new_input&quot; type=&quot;text&quot; id=new_',i,'>
')
}
row_change=as.data.table(row_change)
setnames(row_change,colnames(old_row))
DT=rbind(old_row,row_change)
rownames(DT)&lt;-c(&quot;Current values&quot;,&quot;New values&quot;)
DT

},escape=F,options=list(dom='t',ordering=F),selection=&quot;none&quot;
)

 </pre>
<p>So, we are putting the old values in the first row and the second is composed of numerical and text input. Their id is new_name_of_the_col, we will use this id to match it with the colnames later on.<br>
Again, Shiny should not escape the characters,  the other options are just here to improve the render (not search field).</p>
<h4><strong>h.How to catch these new fields ?</strong></h4>
<p>Now that the fiels are created Shiny need to be able to detect them and use them as an input. As previously, we’ll create a custom shiny input with js:</p>
<pre>
 tags$script(HTML(&quot;$(document).on('click', '#save_changes', function () {
var list_value=[]
for (i = 0; i &lt; $( '.new_input' ).length; i++)
{
list_value.push($( '.new_input' )[i].value)
}
Shiny.onInputChange('newValue', list_value)
});&quot;))
 </pre>
<p>What is the script doing ? When the user click on the action button <em>save_changes</em>, it will collect all the input of class <em>.new_input</em> (the class we set for the new fields) and push them in a list. This list will be assigned to <em>input$newValue .</em></p>
<p>Input$new_value will hence be observed in Shiny:</p>
<pre>
 observeEvent(input$newValue,
{
newValue=lapply(input$newValue, function(col) {
if (suppressWarnings(all(!is.na(as.numeric(as.character(col)))))) {
as.numeric(as.character(col))
} else {
col
}
})
DF=data.frame(lapply(newValue, function(x) t(data.frame(x))))
colnames(DF)=colnames(vals$Data)
vals$Data[as.numeric(gsub(&quot;modify_&quot;,&quot;&quot;,input$lastClickId))]&lt;-DF

}
)
 </pre>
<p>The first lapply is used to cast the input to the right type (in our case numeric or character). Then, it is put in a data.frame with appropriate colnames. Finally, we can get the proper row to change by using the last modify button the user clicked on.</p>
<p>Here we are, the apps should work perfectly now !</p>
<p><strong>You can find the code <a target="_blank" rel="nofollow" href="https://github.com/AntoineGuillot2/ButtonsInDataTable">HERE.</a></strong></p>
<p>Thanks for reading the tutorial,<br>
Antoine</p>
<p>You can follow me on Twitter:</p>
<p><a data-text-color="#111111" target="_blank" class="twitter-follow-button" data-link-color="#0093c2" rel="nofollow" href="https://twitter.com/AntGuilllot" data-show-count="false">Follow @AntGuilllot</a></p>
<p> </p>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/antoineguillot.wordpress.com/1190/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/antoineguillot.wordpress.com/1190/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Qvpqw1wUzSs">