R - Conditional row highlighting in HTML table created using xtable or kable

后端 未结 4 1146
天命终不由人
天命终不由人 2020-12-30 05:55

I\'m pretty much a beginner at programmatically formatting R output, but I\'ve got a basic understanding of knitr, xtable, Markdown, and Pandoc\'s

4条回答
  •  我在风中等你
    2020-12-30 06:37

    Here is a solution using Gmisc::htmlTable

    set.seed(123)
    df <- data.frame(id       = sample(1:100, 20, replace = TRUE),
                     inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
                     outcome  = sample(1:4, 20, replace = TRUE))
    
    cols <- with(df, ifelse(outcome == 1, 'magenta', 'white'))
    
    library(Gmisc)
    htmlTable(as.matrix(df), altcol = cols, 
              rgroup = '', n.rgroup = rep(1, length(cols)))
    

    EDIT

    Since htmlTable has since been moved to the package, htmlTable, and is no longer in Gmisc >= 1.0, the new way to do this would be

    library('htmlTable')
    htmlTable(as.matrix(df), col.rgroup = cols)
    

    which also gives:

    enter image description here

    and your markdown code would simply be

    ```{r, results='asis'}
    htmlTable(as.matrix(df), altcol = cols, 
              rgroup = '', n.rgroup = rep(1, length(cols)))
    ```
    

    And my .Rmd would look like:

    ---
    output: 
      html_document:
        css: ~/knitr.css
    ---
    
    ```{r, results='asis', message=FALSE}
    set.seed(123)
    df <- data.frame(id       = sample(1:100, 20, replace = TRUE),
                     inputval = sample(seq(0, 1, by=0.01), 20, replace = TRUE),
                     outcome  = sample(1:4, 20, replace = TRUE))
    
    cols <- with(df, ifelse(outcome == 1, 'magenta', 'white'))
    
    library(Gmisc)
    htmlTable(as.matrix(df), altcol = cols, 
              rgroup = '', n.rgroup = rep(1, length(cols)))
    ```
    

提交回复
热议问题