-->

R Shiny DataTables: Format numbers not by column b

2019-05-25 18:14发布

问题:

My data is a matrix like this:

             Buy and Hold              Strategy
[1,]    1.0000000000000000   19.0000000000000000
[2,]   -0.6300786023496699   -0.2361973739022651
[3,]   -0.0872213557701079   -0.0244237977843418
[4,]   -0.3461103323781194   -0.1010012410191289
[5,]    0.0000000000000000    0.4949083503054990
[6,]    0.2520044841505053    0.2418168087629348
[7,]   -0.7946470924762163   -0.7731378277502762
[8,] 1864.0000000000000000 1707.0000000000000000

As you see I need a formatting by row and not by column. For example [1,] should be without decimals, so there is a 1 and a 19. However Rows [2,]-Row[7,] should be a percentage like xx.x% and Row[8,] again a number without decimals. How can I achieve that? I have no clue how to use these callback functions and I assume there lies the solution..

回答1:

You can use the rowCallback functions:

library(DT)

data <- matrix(c(0,0.64,-0.76234,0.43,1,19),nrow=3,byrow=T)

    datatable(data,options=list(
            rowCallback=JS("function( row, data, index ) {
                           $('td:eq(0)', row).html(data[0] % 1 != 0 | data[0]==0 ? (data[0]*100).toFixed(1) +'%':data[0]);
                           $('td:eq(1)', row).html(data[1] % 1 != 0 | data[1]==0 ? (data[1]*100).toFixed(1) +'%':data[1]);
                           }
                           ")))

This example will multiply the number by 100, round to 1 decimal and add a percent sign if the number has a decimal part or if it is 0. If not, it leaves the number as is.

It is only doing this on the first and second column of the datatable.



标签: r shiny dt