Introducing the Weighted pickerInput Module for Shiny

Reading time:
time
min

In data analysis, dashboards are essential tools for making sense of complex data. Dashboards help to derive insights that drive better decision-making. However, as the volume and complexity of data increases, so does the challenge of presenting it in a clear and meaningful way.

Sometimes the variety of Shiny inputs is not enough. And there is a need to allow the user to set up inputs in a descriptive way; here come the new libraries or manual approaches.

In this article, we will introduce an improvement to the "shinyWidgets::pickerInput" function. The new feature adds to this input a possibility to assign weights to each of the selection’s options. We’ll explore how this new feature can be used to customize dashboards, and identify trends and patterns in the data more easily.

TOC:
<ul><li><a href="#run">Running the Weighted Picker Input Shiny Application</a></li><li><a href="#demo">Exploring Weighted Picker Input Shiny Demo</a></li><li><a href="#import">Import pickerInput Module to Shiny</a></li><li><a href="#js">JavaScript Customization of pickerInput</a></li><li><a href="#modifiers">Add pickerInput Weight Modifiers</a></li></ul>
[video width="512" height="549" webm="https://wordpress.appsilon.com/wp-content/uploads/2023/05/example-of-pickerInput-in-Shiny-with-custom-javascrip.webm"][/video]

<hr />

<h2 id="run">Run the Weighted Picker Input Shiny Application</h2>
Clone the full code from the <a href="https://github.com/Appsilon/weighted-picker-input">Github repository.</a>

Here is the folder structure you need to start the demo application.
<pre><code>
├── app.R
├── weightedPickerInput.R
└── www
   ├── css
   │   └── styles.scss
   └── js
       └── index.js
</code></pre>
Ensure that you have installed all the necessary libraries on your local machine.
<pre><code>
library(sass)
library(shiny)
library(bslib)
library(glue)
library(shinyWidgets)
library(dplyr)
library(tibble)
library(stats)
library(scales)
</code></pre>
Finally, run the application and let’s explore it!
<pre><code>shiny::runApp()</code></pre>
<h2 id="demo">Exploring the Weighted Picker Input Shiny Demo</h2>
Now you are able to assign the most important criterias that you take into consideration when choosing the car, and select the best car from the `mtcars` dataset. 

For instance, let’s imagine that you are already subscribed to our <a href="https://www.linkedin.com/newsletters/6954735389467107328/" target="_blank" rel="noopener">Data4Good Newsletter</a>, and optimal fuel consumption is the most important metric for you. Let’s assign the score of mpg to the maximum level, with adding other metrics you would like to consider.

<img class="aligncenter size-full wp-image-18955" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01b4781e2982979e02100_pickerInput-in-Shiny-mtcars-dataset.webp" alt="pickerInput in Shiny mtcars dataset" width="368" height="335" />

You can try to assign higher values for some of the options to see how it affects the results. Please note that the dataset is normalized; it prevents some features from dominating others.

<img class="aligncenter size-full wp-image-18959" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01b49fdb8ad62e9cb11f3_weighted-pickerInput-in-Shiny.webp" alt="weighted pickerInput in Shiny" width="683" height="491" />

You may also want to group choices, and our code sharpened for such use cases, see the example below. Developers can also specify such arguments like min, max, default numbers of range, step of the change, etc.
<pre><code>
weightedPickerInput(
"months",
label = "Options",
list(
  Winter = month.name[1:3],
  Spring = month.name[4:6],
  Summer = month.name[7:9],
  Fall = month.name[10:12]
),
min_weight = 0,
max_weight = 1,
default_weight = 0.5,
step = 0.1
 ),
</code></pre>
<img class="aligncenter size-full wp-image-18957" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b01b4a04c5410aa96beeb1_pickerInput-in-Shiny-with-custom-JavaScript.webp" alt="pickerInput in Shiny for month select" width="380" height="748" />

If it’s not possible for you to run the application on your own machine. You can go to the deployed version of the <a href="https://connect.appsilon.com/weighted-select-input/">Shiny Weighted Select Input example</a>.


<h2 id="import">Import pickerInput module to Shiny</h2>

Then let’s consider the creation of the current module in R. We create the JS function with all the logic explained above and wrap the typical pickerInput with a div block that has a defined class for styling.


weightedPickerInput <- function(
	id,
	choices,
	label = NULL,
	selected = NULL,
	min_weight = 1,
	max_weight = 5,
	default_weight = 3,
	step = 1
  ) {

  constants <- glue(
	"{
  	minWeight: {{ min_weight }},
  	maxWeight: {{ max_weight }},
  	defaultWeight: {{ default_weight }},
  	step: {{ step }},
	}",
	.open = "{{",
	.close = "}}"
  )

  # 1 dimension vector should be wrapped into the list
  if (is.null(names(choices))) {
	choices = list(` ` = choices)
  }

  div(
	class = "weighted-stats-selector",
	pickerInput(
  		inputId = id,
  		label = label,
  		choices = choices,
  		multiple = TRUE,
  		selected = selected
	),
	tags$script(
  		glue("initStatsWeightModifier('{id}', {constants})")
	)
  )
}


From here, you can easily add your module to the code, but do not forget about the adding styles and JS to your UI.

<pre><code>css &lt;- sass(sass_file("www/css/styles.scss"))
# Define UI for application that draws a histogram
ui &lt;- fluidPage(
 theme = bs_theme(5),
<br>  # make sure that js and css are set and added
 tags$head(tags$style(css)),
 tags$head(tags$script(src = "js/index.js")),
 
 weightedPickerInput(
"car_options",
c("mpg", "disp", "hp", "drat", "wt", "qsec"),
selected = NULL
 )
)</code></pre>


If you want to get the state of this input inside the Shiny application, the only thing you need to do is:


<pre><code>
observeEvent(input$`car_options-stats_weights`, {
 state &lt;- input$`car_options-stats_weights`
 weights &lt;- state$weights
})</code></pre>


Styling the control buttons are described in the <a href="https://github.com/Appsilon/weighted-picker-input/blob/main/www/css/styles.scss" target="_blank" rel="noopener">sass file</a>. You can adjust the styling that suits your needs or customize the colors of pickerInput.

<h2 id="js">JavaScript Customization of pickerInput</h2>
For creating such a solution, we needed to use some custom JavaScript techniques. The most important actions taken are described below, but you can also explore the full code on our <a href="https://github.com/Appsilon/weighted-picker-input/blob/main/www/js/index.js" target="_blank" rel="noopener">weighted pickerInput repo</a>. 

Get the current pickerInput element, and then add listeners for each of the selector options.


<pre><code>
const select = document.getElementById(id);
select.addEventListener('change', () =&gt; {
const options = select.parentNode.querySelectorAll('.dropdown-item.opt');
[...options].forEach((option) =&gt; handleWeightsVisibility(option));
sendStateToShiny();
 });
<br>const sendStateToShiny = () =&gt; {
 Shiny.setInputValue(`${id}-stats_weights`, { weights: weightsState });
};
</code></pre>


<h3 id="modifiers">Add pickerInput Weight Modifiers</h3>
`handleWeightsVisibility` controls whether to show the weight selection, because it should be visible only for the selected options. The `addWeightModifiers` and `removeWeightModifiers` functions manage adding and removing modifiers elements to the actual DOM structure accordingly.


<pre><code>
const addWeightModifiers = (option, step) =&gt; {
 const modifier = option.querySelector('.weight-modifier');
 const statName = getStatName(option);
 if (weightsState[statName] === undefined) weightsState[statName] = defaultWeight;
 if (!modifier) option.appendChild(weightModifier(statName, step));
};
const removeWeightModifiers = (option) =&gt; {
 const modifier = option.querySelector('.weight-modifier');
 const statName = getStatName(option);
 if (modifier) option.removeChild(modifier);
 if (weightsState[statName] !== undefined) delete weightsState[statName];
};
const handleWeightsVisibility = (option, initial = false) =&gt; {
 if (option.classList.contains('selected') || initial) {
addWeightModifiers(option, step);
 } else {
removeWeightModifiers(option);
 }
};
</code></pre>


So if the user selects some option, `weightModifier` creates a `controlButton` element and adds it to the current option with the default weight value.

<pre><code>
const weightModifier = (statName, step) =&gt; {
 const modifier = document.createElement('div');
 modifier.className = 'weight-modifier';
 modifier.addEventListener('click', (e) =&gt; e.stopPropagation());
 modifier.append(
controlButton(statName, 'decrease', step),
weightValue(statName),
controlButton(statName, 'increase', step),
 );
 return modifier;
};
</code></pre>


And `updateWeight` function changes the value of the current `controlButton` modifier, by the user’s click on <i>increase/decrease</i> buttons.

<pre><code>
const controlButton = (statName, action, step) =&gt; {
 const button = document.createElement('button');
 button.className = 'btn btn-outline-primary control-btn';
 button.classList.add(action);
 button.textContent = action === 'increase' ? '+' : '-';
 button.addEventListener(
'click',
(e) =&gt; {
  const newWeightValue = updateWeight(e, statName, action, step);
  updateControlButtons(button, action, newWeightValue);
},
 );
 return button;
};
</code></pre>


The JS tracks changes to the controlButton element, and it immediately sends the current state of the pickerInput to Shiny when any changes are made through an updateWeight call.

<pre><code>
const updateWeight = (e, statName, action, step = 1) =&gt; {
 e.stopPropagation();
 const currentValue = weightsState[statName];
 const valueNode = e.target.parentNode.querySelector('.weight-value');
 let newValue;
 if (action === 'increase') {
newValue = currentValue &lt; maxWeight ? currentValue + step : maxWeight; } else if (action === 'decrease') { newValue = currentValue &gt; minWeight ? currentValue - step : minWeight;
 }
 weightsState[statName] = newValue;
 valueNode.textContent = parseFloat(newValue.toFixed(2));
 sendStateToShiny();
 return newValue;
};
</code></pre>


<h2 id="conclusion">Conclusions on pickerInput in Shiny</h2>


Usage of this approach can enhance the user experience in dashboards. It provides more control over the way options affect the data, so users can easily specify the information they want to explore. It allows users to rank and filter data, based on weighted criteria and improve the decision-making process.

We hope that you like this solution. You can integrate weighted selector in areas like finance, risk assessment, healthcare etc.

Have questions or insights?

Engage with experts, share ideas and take your data journey to the next level!

Is Your Software GxP Compliant?

Download a checklist designed for clinical managers in data departments to make sure that software meets requirements for FDA and EMA submissions.
Explore Possibilities

Share Your Data Goals with Us

From advanced analytics to platform development and pharma consulting, we craft solutions tailored to your needs.

Talk to our Experts
r
shiny
UI/UX