Swap numbers for words and organize so strings come before numbers

Within a Shiny application, I encounter a scenario where a column of numbers in a datatable has certain values suppressed for security reasons. To maintain confidentiality, these suppressed values are replaced with a specific string referred to as "my_string". When this column is sorted, it is essential that the suppressed values are treated as if they are lower than all actual numbers. These suppressed values are denoted by -1, while all other values in the column are positive integers.

My initial approach involved recoding the -1 as "my_string", which converted the entire column into a character type. By utilizing the natural plug-in to sort the character-coded numerics appropriately, I aimed to achieve the desired sorting order. However, during execution, "my_string" ended up being sorted above all numeric values, contrary to my expectations.

An alternative method could involve implementing a JavaScript callback to substitute the -1 with the designated string. Nevertheless, lack of expertise in scripting and integrating it effectively within the datatable poses a challenge.

The code snippet provided attempts to incorporate the natural plug-in. Ideally, "my_string" should appear at the bottom rather than the top of the list, reflecting the correct sorting order.

# Sample dataset illustrating the data structure
my_mtcars <- mtcars[1:6, 1:4]
my_mtcars[1, 4] <- -1

# Recoding the suppressed value (-1)
my_mtcars[my_mtcars == -1] <- 'my_string'

# Implementation within our demonstration app.R file
library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput('example')
)

server <- function(input, output) {
  output$example <- renderDataTable(
    my_mtcars,
    server = FALSE,
    plugins = 'natural',
    options = list(columnDefs = list(list(type = 'natural', targets = '_all')))
  )
}

shinyApp(ui = ui, server = server)

https://i.sstatic.net/1d6h1.png

Answer №1

If you're looking for a simpler solution, consider using a custom formatter or column render function.

Check out the Column Rendering section in the DT documentation:

You can also refer to the DataTables documentation for more information: https://datatables.net/reference/option/columns.render

my_mtcars <- mtcars[1:6, 1:4]
my_mtcars[1, 4] <- -1

formatSuppressedValues <- JS("
  function(data, type) {
    if (type !== 'display') return data;
    if (data !== -1) return data;
    return 'my_string';
  }
")

library(shiny)
library(DT)

ui <- fluidPage(
  DT::dataTableOutput('example')
)

server <- function(input, output) {
  output$example <- DT::renderDataTable(
    my_mtcars,
    server = FALSE,
    options = list(
      columnDefs = list(list(
        targets = '_all',
        render = formatSuppressedValues
      ))
    )
  )
}

shinyApp(ui = ui, server = server)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the findIndex method to search for an element starting at a designated index

Below is a snippet of code that I have: private getNextFakeLinePosition(startPosition: number): number{ return this.models.findIndex(m => m.fakeObject); } This function is designed to return the index of the first element in the array that has ...

Using R to subset time series data into intervals of two years

My goal is to create a model using autoarima with time-series data spanning from 1970 to 2015. I am interested in observing how the model predicts based on different lengths of historical data. For example, predicting 2005 using only one year of data (19 ...

If I click on the datalist link option during an ajax append, I would like to be redirected

When I try to link after clicking an option in the appended AJAX, it does not seem to work as expected: More details: $('#input-friends').on('input', function () { var id = $('#input-friends').val(); $.ajax({ ...

Exploring jQuery Mobile: Uncovering the Power of clientX, clientY, and taphold Event

In my current project, I am implementing the taphold event and require the coordinates of the tapped point by the user. However, I have encountered an issue where event.clientX and event.clientY are returning as undefined (you can see the example here: her ...

Is there a way to incorporate a confirmation prompt into this code?

My jQuery code is below: $('.delete_step').live('click', function(e) { e.preventDefault(); var delete_location = window.location.pathname.replace('admin/', '') + '?route=module/cart/delete_step'; ...

What is the process for creating a new variable with a condition in R for long-format data sets?

I'm currently working on creating a new conditional variable called evHab for my dataset that is in long format. Here is the data I am analyzing: canton surfHab year Appenzell 377.2 1979-85 Appenzell 379.3 1992-97 Appenzell 42 ...

Choosing the initial option in an AngularJS radio button

I need to set the default selected value of a radio button to 3. The code I am using is: <div class="checkbox-group" ng-init="ac.ServiceCode=3"> <input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change=' ...

A step-by-step guide on integrating the CSS file of react-datepicker into a Nestjs SSR application with AdminJS

Currently, I am integrating the react-datepicker component into my SSR project built with Nest.js and Admin.js. To ensure that the React components function properly and are styled correctly, I need to include the line 'import 'react-datepicker/d ...

Is there a way to accurately determine which element a delegate was clicked on?

Whenever a user clicks on a table row (TR), I want to implement functionality where the checkbox is checked, similar to Google Drive / Google Docs. However, there are exceptions for checkboxes or any <a> tags as they have different actions. If the u ...

Having trouble updating a variable's state with setState on click

Struggling with a consistent issue while working on a React project. The problem lies in setting a variable into state using setState upon a click event. Specifically, I am facing difficulty passing my player object into state as ActivePlayer when the co ...

The website on iPad automatically zooms in upon opening and then increases the zoom level even further when a specific button is tapped

I recently coded a website using html, css, and js. It seems to work perfectly on all devices except for the iPad. Interestingly, when I use the iPad emulator in Google Chrome, everything appears normal. However, when I open the website on an actual iPad, ...

Choosing specific columns using sym and enquo in the dplyr::select function

BLUP: How can I pass column ranges to `dplyr::select` using `sym` and `enquo`? Let's say we have a tibble with columns A through E: library(tibble) library(dplyr) set.seed(4) d = as_tibble(setNames(as.list(rnorm(5)), LETTERS[1:5])) d ## # A tibble: ...

The function provided in the props is not considered as a function

Trying to send a function named addtodo as a prop from one class to another, I have successfully passed the function using the following code: export class Todo extends Component { constructor(props) { super(props); this.state = {todos ...

Is there a way to gradually reveal JSON data without continuously re-parsing and displaying it on a webpage?

Currently, I am working with a log file that is constantly updated by a running script in real-time. My goal is to effectively monitor the status of this script on a web page using HTML and JavaScript. To achieve this, I have utilized JavaScript to dynamic ...

Altering CSS according to scroll position and anchor points

Currently on my website, I have users clicking on navigation links that turn the backgrounds yellow when clicked. I saw a similar effect on On this site, when a user scrolls to an anchor in the document, the corresponding navigation element is highlighte ...

How can you form a promise by combining multiple asynchronous file reads in Node.js?

Consider the following scenario: fn1() { [filepath1, filepath2, ..., filepathN].forEach(process); function process(path) { fs.readFile(file, translate); } } The callback function translate operates on the contents of each file. How can ...

Encountering a JavaScript error occurring within an iframe interface

Let's discuss the current scenario: A webpage (iframe.html) contains an iframe that loads another page (iframe-content.html). There is a possibility of a JavaScript error occurring when iframe-content.html is loaded within the iframe. The goal is to ...

Generate an Origin/Destination table in R using a DataFrame

Hello everyone, I'm currently facing a challenge in creating an Origin/Destination table based on my Data Frame (DF). The DF contains trip numbers, stop indices, departure times at each stop, and stop names: Trip Index Departure Time OD 16 1 a ...

Unveiling the Mystery: How Browser Thwarts Server Push in HTTP/2.0

After studying the documentation of HTTP/2.0, I discovered that it is feasible to completely close a referenced stream using the RST_STREAM frame. Check it out here: ()! I am curious about how this feature can be implemented in popular web browsers such a ...

Issue with display of absolute/relative positioned element in IE8

Within a list element (a div) styled with inline-block, there is a ul positioned relatively that is initially hidden. To make the div absolute, I added a class but encountered issues specifically in IE8/9 where clicking on the list does not reveal it as ex ...