在 R Datatable 中,他们是一种有条件地向数字添加加号的方法吗?

In R Datatable is their a way to conditionally add a plus sign to a number?

我的 table 中有一列是百分比变化,所以我想将其显示为加号或减号。问题是我仍然希望它是 sortable 所以它需要是数字而不是字符串。

我假设可以在数据table 格式中做一些事情来为大于 0 的任何内容添加一个加号,但根据文档无法弄清楚。我需要第 4 列前面有一个 plus/minus。这是我的出发点:

  datatable(temp,rownames=F,options = list(dom='t'))%>%
  formatStyle("Change",
              backgroundColor  = styleInterval(c(-.10,-.075, -.05, -.025,-.0175, 0,.0175, .025, .05, .075, .10), 
                                               c('#f79539','#fab83e','#f7e38f','#fffcc9','#fffee6', '#ffffff','#ffffff','#fffee6','#fffcc9','#f7e38f','#fab83e', '#f79539' )))  %>%
  formatPercentage(c(2:4), 2) 

使用render:

library(DT)

render <- c(
  "function(data, type, row) {",
  "  if(type === 'display') {",
  "    var sign = data > 0 ? '+' : '-';",
  "    return sign + data;",
  "  } else {",
  "    return data;",
  "  }",
  "}"
)

df <- data.frame(
  Val = c("A", "B"), 
  x = c(-1, 1)
)
datatable(df, 
          options = list(
            columnDefs = list(
              list(targets = 2, render = JS(render))
            )
          )
)