【问题标题】:In R Datatable is their a way to conditionally add a plus sign to a number?在 R Datatable 中,他们是一种有条件地向数字添加加号的方法吗?
【发布时间】:2021-02-11 05:41:27
【问题描述】:

我的表格中有一个列是百分比变化,所以我希望它显示为正数或负数。问题是我仍然希望它是可排序的,所以它需要是数字而不是字符串。

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

  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) 

【问题讨论】:

    标签: r datatables formatting dt


    【解决方案1】:

    使用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))
                )
              )
    )
    

    【讨论】:

    • 似乎当我在其上使用 formatPercentage 时,它​​会覆盖对渲染的使用。他们是通过渲染完成格式百分比的方法吗?我不熟悉该代码,所以我不知道如何进行更改。
    • @bpheazye return sign + data + '%';
    • 谢谢斯蒂芬!只是为了那些后来发现这个来完全模拟 formatPercentage 函数使用 tofixed render &lt;- c( "function(data, type, row) {", " if(type === 'display') {", " var sign = data &gt; 0 ? '+' : '-';", " return sign + (100*data).toFixed(2) + '%';", " } else {", " return data;", " }", "}" )
    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2013-05-30
    • 2011-06-16
    • 2022-07-22
    相关资源
    最近更新 更多