2
votes

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
what's the criteria for being a % or without a decimal, for example is 0.000000000 on line 5, first column a 0% or a 0? Or is it that if both columns have no decimals, they are not percentages?NicE
Basically everything is a% except row 1 and 8 which are normal numbers without decimals and no percentageMichiZH
Yes is 0.0000000000 a normal number or a percentage (row 5 first column)NicE
Ah that should be a percentage, so 0.0%MichiZH

1 Answers

5
votes

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.