Mark
Mark

Reputation: 2899

How to format a column 1 way, but 1 row in that column another way in R datatable (DT)

I'm struggling with a DT issue where I want to format 1 column as scientific annotation, but some values in this column are percentage values as the table I am dealing with.

If I change the value in the table to paste(n, "%", sep = ' ') beforehand, the rowcallback gets stuck on non numeric value

in either scenario I can use either the rowcallback (see below) to format scientific annotation OR the other case, use formatPercentage('columnname', 2) to format a column in percentages, but I would like to do both to one column, and a single row therein that I need to be presented as 'n % while the rest of the column is in scientific an.

Is there a way to perform a rowcallback on 1 column, but exclude specific rows,

OR combine a rowcallback for scientific annotation, and format the other cells that are percentages as percentage (x %)

The datatable below generates the sci. an. but how to alter cars[5,2] to a 2 decimal % value with % symbol behind it?

datatable(cars/10, 
          options = list(
                 rowCallback = JS(
      "function(row, data) {",
      "    $('td:eq(2)', row).html(data[2].toExponential(1));",
      "}")
          )
)

Upvotes: 2

Views: 551

Answers (2)

Stéphane Laurent
Stéphane Laurent

Reputation: 84599

Formatting the column in R is not a nice option because the column type would become character and you would lost the possibility to sort the column. Here is the JavaScript way to go:

datatable(cars/10, 
          options = list(
            rowCallback = JS(
              "function(row, data, num, index){",
              "  if(index != 4){",
              "    $('td:eq(2)', row).html(data[2].toExponential(1));",
              "  }else{",
              "    $('td:eq(2)', row).html((100*data[2]).toFixed(2) + '%')",
              "  }",
              "}")
          )
)

enter image description here

Upvotes: 2

demarsylvain
demarsylvain

Reputation: 2185

In order to have scientific annotation, you can use the function formatC() with the argument format = 'e' and digits = 1.

formatC(cars$dist[1:5] / 10, format = 'e', digits = 1)
# [1] "2.0e-01" "1.0e+00" "4.0e-01" "2.2e+00" "1.6e+00"

To make percentage visualisation, as formatPercentage() will transform all the column, you can make it yourself with paste().

Then, just create a condition to tell, with ifelse() for instance, when using the scientific format, and when using the percentage one.

cars %>% 
  mutate_all(funs(. / 10)) %>% 
  mutate(Condition = 1:n()) %>% 
  mutate(dist = ifelse(Condition == 5,
                       paste(round(dist, 2), '%'),
                       formatC(dist, format = 'e', digits = 1))
  ) %>% 
  select(-Condition) %>% 
  datatable()

enter image description here

Upvotes: 0

Related Questions