[英]R - Formatting by row using DT
I have a data table that I want to display in a Shiny app with different number formatting by row. 我有一个要在Shiny应用程序中显示的数据表,该数据表按行具有不同的数字格式。 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 我找到了用户NicE的先前解决方案,该解决方案在所有列和行均为数字时都可以使用,如下所示: R Shiny DataTables:不按列而是按行格式化数字
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. 不幸的是,我的第一列是非数字的,并且在我的表中,上述解决方案在第一列中给出了NaN%的值,并且不格式化后面的列。 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. 我确定有解决此问题的方法,但是我不知道JavaScript,所以我不知道如何正确修改rowCallback函数。
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. 然后在dat2而不是dat上运行datatable(...)。 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. 这样会导致行名的NaN%相同,但是现在第一个实际的列已正确设置了格式,但其余列却未正确设置。
Start at j=2
when you do td:eq(j)
. 当您执行td:eq(j)
时,从j=2
开始。 This discards the 0
-th column (the column of row names) and the 1
-th column. 这将丢弃第0
列(行名的列)和第1
列。 I also add if(index>0)
to discard the first row (indexed by 0
in Javascript). 我还添加了if(index>0)
来丢弃第一行(在Javascript中由0
索引)。 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) + '%');",
" }",
" }",
"}"
))
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.