kableExtra : How can i set to bold the biggest value of the row?

↘锁芯ラ 提交于 2021-02-11 15:17:52

问题


Suppose i have a table that looks like :

x = matrix(runif(10*5),nrow=10,ncol=5)

When i display the matrix using kableextra, i want the highest value, per row, of say the last 2 rows, to be bolded.

I looked at this document https://rdrr.io/cran/kableExtra/f/inst/doc/awesome_table_in_pdf.pdf a lot and i did not found how to use cell_spec correctly to perform this goal.


回答1:


I thought this would be easier than it turned out to be. As far as I can see, this is how to do it:

---
title: "Untitled"
output:  pdf_document
---

```{r}
set.seed(123)
library(knitr)
library(kableExtra)
x <- matrix(round(runif(10*5),2), nrow=10,ncol=5)
j1 <- which.max(x[9,])
j2 <- which.max(x[10,])
col <- seq_len(ncol(x))
x[9,] <- x[9,] %>% cell_spec(bold = col == j1)
x[10,] <- x[10,] %>% cell_spec(bold = col == j2)
x %>% kable(booktabs = TRUE, escape = FALSE)
```

A few notes:

  • I rounded the values so they aren't so ugly when printed.
  • I couldn't see a way to do everything in one pipeline, though there probably is one. The trouble is that cell_spec is designed to work on vectors, not matrices.
  • Finally, the escape = FALSE in kable() is essential: otherwise you'll see the code to make it bold, rather than the bold entry itself.


来源:https://stackoverflow.com/questions/61391380/kableextra-how-can-i-set-to-bold-the-biggest-value-of-the-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!