block by timelyportfolio 9aa6fcc0e3b8bbe6dad7

rCharts + datatables | sort with scientific notation

Full Screen

Sort with Scientific Notation using rCharts + datatables

In rCharts issue #458, the question asked was

How do I sort with scientific notation as shown in Datatables scientific sorting plugin?

Here is a sample set of code how we can accomplish this using a modified iris dataset. To see it, go to the rCharts viewer or play with it live.

iris_sc <- iris
#randomly make these numbers exponentially large to be able to visually verify result
iris_sc[,-5] <- format(iris_sc[,-5]*10^runif(nrow(iris),1,10),scientific=T)

dt <- dTable(
  iris_sc[sample(1:nrow(iris_sc),50),]
)
#add the scientific sort from http://next.datatables.net/plug-ins/sorting/scientific
#easier to add in script than to add to jshead
dt$setTemplate(chartDiv = sprintf('%s
  <script>
    %s
  </script>
  ',
  dt$templates$chartDiv,
  'jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "scientific-pre": function ( a ) {
      return parseFloat(a);
    },

    "scientific-asc": function ( a, b ) {
      return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "scientific-desc": function ( a, b ) {
      return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
  } );
  '
))
#hack with lapply; I think there is a better way to do
#but this sets type to scientific for all columns
#except the last which is species
dt$params$table$aoColumns[-ncol(iris_sc)] <- lapply(
  dt$params$table$aoColumns[-ncol(iris_sc)],
  function(x){
    x$sType = "scientific"
    return(x)
  }
)
dt

index.html

code.R