R Shiny DataTables:不按列而是按行格式化数字 [英] R Shiny DataTables: Format numbers not by column but by row

查看:67
本文介绍了R Shiny DataTables:不按列而是按行格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是这样的矩阵:

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

如您所见,我需要按行而不是按列进行格式化。例如[1,]应该不带小数,因此有1和19。但是[2,]-Row [7,]行应为xx.x%的百分比,而Row [8,]应为数字不带小数。我该如何实现?我不知道如何使用这些回调函数,并且我认为解决方案就在这里。

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..

推荐答案

您可以使用 rowCallback 函数:

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]);
                           }
                           ")))

此示例将数字乘以100,四舍五入到小数点后1位,如果数字有小数部分或为0。如果没有,则数字保持原样。

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.

仅在第一和第二位执行此操作数据表的ond列。

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

这篇关于R Shiny DataTables:不按列而是按行格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆