R Shiny DataTables: Format numbers not by column but by row

偶尔善良 提交于 2019-12-08 01:01:07

问题


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.



来源:https://stackoverflow.com/questions/33916578/r-shiny-datatables-format-numbers-not-by-column-but-by-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!