DMartin
DMartin

Reputation: 33

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

Upvotes: 3

Views: 1616

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

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) + '%');",
    "    }",
    "  }",
    "}"
  ))
))

enter image description here

Upvotes: 3

Related Questions