【问题标题】:Kable highlighting the largest value in each row (R - Knitr)Kable 突出显示每行中的最大值 (R - Knitr)
【发布时间】:2022-11-22 02:12:31
【问题描述】:

让我们使用这个数据框:

x <- structure(list(`A. afarensis` = c(NaN, 41.624448481617, NaN, 
44.3444026007235, 45.637877314444), `A. africanus` = c(NaN, 40.8108406931158, 
NaN, 17.6702611050343, 28.8624817479424), `A. anamensis` = c(NaN, 
3.96543899879134, NaN, 13.4563973882188, 7.02306143133709), `Ar. ramidus` = c(NaN, 
3.31720723035651e-05, NaN, 0.00154294031842416, 7.49122553868537e-05
), Australopithecus = c(NaN, 6.97874566506872, NaN, 4.99347711237018, 
6.04930517572641), tooth = c("M1", "M1", "M1", "M1", "M1")), row.names = c("1", 
"2", "3", "4", "5"), class = "data.frame")

我想用粗体和红色背景颜色突出显示每行的最高值,从列A. afarensisAustralopithecus

我创建了这个功能:

fun_kable <- function(data){
  kable(data, digits = 2) %>%
    kable_classic(full_width = T, 
                  html_font = "Cambria", 
                  font_size = 10) %>%
    column_spec(ncol(data), bold = T, italic = T, color = "red")
}

当我运行 fun_kable(x) 时,我还想查看每行的最高值。我怎么能通过使用以前的功能来做到这一点?

【问题讨论】:

    标签: r dataframe knitr kable kableextra


    【解决方案1】:

    这是一种使用cell_spec()的方法。请注意,舍入必须事先完成,因为使用 cell_spec 会将变量转换为字符。如果 Ar.ramidus 列中的三个 0 对您来说有问题,您可以增加位数。

    library(dplyr)
    library(kableExtra)
                                                                                                                                                                                                                                                              "2", "3", "4", "5"), class = "data.frame")
    max_values <- x |> 
      mutate(across(where(is.numeric), round, 2)) |> 
      summarise(across(-tooth, max, na.rm = TRUE)) |> as.vector() |> unname()
    
    x |> 
      mutate(across(where(is.numeric), round, 2)) |> 
      mutate(across(-tooth, ~if_else(row_number() %in% which(.x %in% max_values),
                                   cell_spec(.x,format =  "html",
                                             color = "red", bold = TRUE), as.character(.x)))) |> 
      kable(escape = FALSE) |> 
      kable_classic(full_width = T, 
                    html_font = "Cambria", 
                    font_size = 10)
    

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 2021-10-04
      相关资源
      最近更新 更多