KableExtra conditionally formatting specific rows on a column

此生再无相见时 提交于 2019-12-03 21:12:52

Here's an example that ignores the first and last rows and colours according to value, like you say, but ignores letters.

First, I load the libraries.

# Load libraries
library(knitr)
library(kableExtra)

Next, I create a dummy data frame.

# Create data frame   
df <- data.frame( region1 = c(sample(c(-5:5, letters[1:5]), 10, replace = TRUE)),
                  region2 = c(sample(c(-5:5, letters[1:5]), 10, replace = TRUE)),
                  region3 = c(sample(c(-5:5, letters[1:5]), 10, replace = TRUE)),
                  region4 = c(sample(c(-5:5, letters[1:5]), 10, replace = TRUE)), stringsAsFactors = FALSE )

Here, I define the function for formatting cells. I ignore the first and last rows and check if the character is a letter or number, then colour accordingly.

foo <- function(x, n, nmax){
  cell_spec(x, background = ifelse(is.na(as.numeric(x)), "white",
                                   ifelse(n == nmax | n == 1, "white",
                                          ifelse(x > 1, "red",
                                                 ifelse(x < 1, "green", "yellow")))))
}

Finally, I apply the function.

df %>% 
  mutate_all(funs(foo(., n = row_number(), nmax = n()))) %>% 
  kable(escape = FALSE) %>% 
  kable_styling()

That's not a good design for a dataframe: columns need to be all one type, so your numbers will be coerced to character.

Nevertheless, you can do what you ask for as follows.

fixcol <- function(col) {
  x <- as.numeric(col[2:3])
  x <- cell_spec(x, background = ifelse(x > 1, "red", ifelse(x == 1, "yellow", "green")))
  col[2:3] <- x
  col
}

df <- as.data.frame(lapply(df, fixcol))
kable(df, escape = FALSE)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!