R-使用DT按行格式化 [英] R - Formatting by row using DT

查看:78
本文介绍了R-使用DT按行格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在Shiny应用程序中显示的数据表,该数据表按行具有不同的数字格式。我找到了用户NicE的先前解决方案,该解决方案在所有列和行均为数字时都可以使用,如下所示:


I have a data table that I want to display in a Shiny app with different number formatting by row. I found a previous solution by user NicE that works when all columns and rows are numeric, seen here: R Shiny DataTables: Format numbers not by column but by row

Unfortunately, my first column is non-numeric, and with my table the above solution gives NaN% values in the first column and does not format the later columns. I'm sure there is a way to resolve this, but I do not know JavaScript so I don't know how to modify the rowCallback function properly.

Here's my current attempt:

library(DT)
dat <- as.data.frame(matrix(c("# respondents",20,35,18,"involvement rate",.85,.8285,.8889,"target",.80,.85,.9),nrow=3,byrow=T))

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

Any help is appreciated!

Edit: I figured since the only expected character strings would be in the first column, I could change that column to be the row names instead:

dat2 <- subset(dat, select = -1)
rname <- as.vector(dat$V1)
row.names(dat2) <- rname

and then run datatable(...) on dat2 instead of dat. That results in the same NaN% for the row names, but now the first actual column is properly formatted, but not the rest of the columns.

解决方案

Start at j=2 when you do td:eq(j). This discards the 0-th column (the column of row names) and the 1-th column. I also add if(index>0) to discard the first row (indexed by 0 in Javascript). Prealably, make a dataframe with numeric columns.

library(DT)
dat <- data.frame(
  V1 = c("# respondents", "involvement rate", "target"),
  V2 = c(20, 0.85, 0.8),
  V3 = c(35, 0.8285, 0.85),
  V4 = c(18, 0.8889, 0.9)
)

datatable(dat,options=list(
  rowCallback=JS(c(
    "function(row, dat, index) {",
    "  if(index > 0){",
    "    for(var j=2; j<dat.length; j++){",
    "      $('td:eq('+j+')', row).",
    "        html((dat[j]*100).toFixed(1) + '%');",
    "    }",
    "  }",
    "}"
  ))
))

这篇关于R-使用DT按行格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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