html - R : Add CSS color coding in a HTML table

标签 html r dataframe

我需要将 data.frame 导出到 HTML 文件并根据条件为表格单元格的背景着色。

示例数据框:

Name   Low    High    Value1    Value2    Value3
 Ben    3      10       2         5          8
 Cat    3      10       3         9          4
 Dan    3      10       5         7          6

期望输出是这样的:

enter image description here

我用下面的代码生成了 HTML,谢谢你的帮助

HTMLheaderText ="Sample Report"
HTMLfile =HTMLInitFile(outdir     = getwd()
                   , filename = "sample"
                   , extension  = "html"
                   , Title      = "R Output"
                   , CSSFile    = paste(getwd(), "/html_tables.css", sep="")
                   , HTMLframe  = FALSE
                   , useGrid    = FALSE
                   , useLaTeX   = FALSE)

 HTML(HTMLheaderText, file = HTMLfile)
 HTML(dataSet, row.names = FALSE)
 HTMLEndFile()

最佳答案

我找到了我需要的解决方案,尽管这可能不是最好的方法。我在每个单元格中添加了一个跨度,并使用 jquery 动态更改单元格的背景。

HTMLheaderText = "Sample Report"

HTMLfile =HTMLInitFile(outdir     = getwd()
                   , filename = "sample"
                   , extension  = "html"
                   , Title      = "R Output"
                   , CSSFile    = paste(getwd(), "/html_tables.css", sep="")
                   , HTMLframe  = FALSE
                   , useGrid    = TRUE
                   , useLaTeX   = FALSE)

HTML('<script src="./jquery-1.7.2.min.js"></script>', file = HTMLfile)

HTML("<script>
  $(document ).ready(function() { 
   $('.dataframe tr).each(function() { 
    var low = $(this).find('td>span.low').text(); 
    var high = $(this).find('td>span.high').text();
    $(this).find('td>span.value').each(function() {
      $(this).css('color', 'white');
      var value= $(this).text(); 
        if (value> low && value< high) {
          $(this).parent().css('background-color', 'green');
        } else {
          $(this).parent().css('background-color', 'red');
        }
         cpk = Number(Math.round(cpk+'e'+4)+'e-'+4);;
         $(this).text(value);
    });

  })
 });
 </script>", file = HTMLfile)

 HTML(HTMLheaderText, file = HTMLfile)
 HTML(dataSet, row.names = FALSE, digit=5)
 HTMLEndFile()

关于html - R : Add CSS color coding in a HTML table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22604107/

相关文章:

python - 如何在 Python 中将 Excel 工作表另存为 HTML?

jquery - 如何防止菜单单击功能和仅激活双击

HTML+CSS : How do I put this 2 buttons at the same level vertically

reshape 但扩展 R 中的数据

r - 安装 sparkR 时出错

python - *有效地*使用 RPy(或其他方式)将数据帧从 Pandas 移动到 R

Python/Pandas - 更新一组记录的数据

javascript - IE <= 8 相当于 selection.getRangeAt()?

r - Hmisc 描述简短版本

删除组中的值与 R 不匹配的数据框行