R - Formatting by row using DT

北城以北 提交于 2019-12-12 21:40:04

问题


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.

来源:https://stackoverflow.com/questions/53784955/r-formatting-by-row-using-dt

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