xtable for conditional cell formatting significant p-values of table

后端 未结 2 1701
灰色年华
灰色年华 2021-02-07 23:28

I\'m using xtable to generate tables to put in Latex, and was wondering if there\'s a way to have conditional formatting of cells so that all significant p-values are in grey?

2条回答
  •  执念已碎
    2021-02-07 23:59

    Hello try this :

    \documentclass{article}
    \usepackage{color}
    \begin{document}
    
    <>=
    df = data.frame(V1 = LETTERS[1:6], V2 = runif(6, 0, 1))
    df$V3 = ifelse(df$V2 < 0.5, paste0("\\colorbox{red}{", df$V2, "}"), df$V2)
    library(xtable)
    print(xtable(df), sanitize.text.function = function(x) x)
    @
    
    \end{document}
    

    EDIT

    If you have multiple conditions, one solution is to use package dplyr and function case_when :

    set.seed(123)
    df <- data.frame(V1 = LETTERS[1:6], V2 = runif(6, 0, 1))
    
    library("dplyr")
    df %>% 
      mutate(
        V3 = case_when(
          V2 < 0.5 ~ paste0("\\colorbox{red}{", round(V2, 3), "}"),
          V2 >= 0.5 & V2 < 0.8 ~ paste0("\\colorbox{blue}{", round(V2, 3), "}"),
          TRUE ~ formatC(V2, digits = 3)
        )
      )
    #   V1        V2                      V3
    # 1  A 0.2875775  \\colorbox{red}{0.288}
    # 2  B 0.7883051 \\colorbox{blue}{0.788}
    # 3  C 0.4089769  \\colorbox{red}{0.409}
    # 4  D 0.8830174                   0.883
    # 5  E 0.9404673                    0.94
    # 6  F 0.0455565  \\colorbox{red}{0.046}
    

提交回复
热议问题