Leading "+" in numeric col

Hi,
I would like to show a leading "+" in front of positive numbers in a column which is showing (numeric) values.

I already tried the following:
a) formatCurrency with a prefix "+". But this is not condtitional to positive numbers.
b) In my current solution I convert the numbers to characters "manually" first. But now I'd like to filter this column "numerically" (slider). This does not seem to be possible.

datatable(data.frame(change = sample(-5:5)), filter = "top")

How could I do that?

Then, you should do filtering at first and converting at last.

It is kinda strange that someone need a "+" symbol to show a number being positive in data frame. Commonly I see that on a plot instead. Could you share the reason?

Whatever the reason for prefixing positive values with a "+", I put together a small example demoing how to do so using DataTable's createdRow option. It is important to note my example does this cell by cell. In the example i refers to the index of each column in a row, so if particular columns need to be ignored add logic to ignore certain values of i. Remember, in JavaScript indexing starts at 0, so your first column is column 0.

library(DT)

sample_data <- mtcars
sample_data[["mpg"]] <- sample_data[["mpg"]] * -1

datatable(
  data = sample_data,
  options = list(
    createdRow = JS(
      "function(row, data, index) {",
      "  data.forEach((d, i) => {",
      "    row.children[i].innerHTML = (+d && +d > 0) ? `+${ d }` : d;",
      "  });",
      "}"
    )
  ) 
)
3 Likes

@nteetor Thanks, very much. That's exactly what I was looking for.
Had to modify your example slightly since there seems to be a problem with the lambda function:

library(DT)

sample_data <- mtcars
sample_data[["mpg"]] <- sample_data[["mpg"]] * -1

datatable(
  data = sample_data,
  options = list(
    createdRow = htmlwidgets::JS(
      "function(row, data, index) {",
      "  data.forEach(function(d, i) {",
      "    row.children[i].innerHTML = (+d && +d > 0) ? '+'+d : d;",
      "  });",
      "}"
    )
  )
)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.