flextable: bold the maximum value in each row

Viewed 86

I'm trying to bold the maximum value in every row with this code

mtcars %>% 
  flextable() %>%
  bold(max(.[1:32,]))

and got this error: Error in .[1:32, ] : incorrect number of dimensions

I also tried, with inspiration from conditionally bold values in flextable

mtcars %>% 
  flextable() %>%
  bold(~ max(.), 1) 
Error in eval(as.call(f[[2]]), envir = data) : object '.' not found

Removing the . in max(.) doesn't make any difference.

2 Answers

To get the max from every row you can try to overwrite the attributes of your flextable object:

Edit:

As mentioned in the comments it is not recommended to change the object strucutre by hand:

library(magrittr)
mtcars %>% 
  flextable::flextable()  -> bold_flex2

for(i in seq_len(nrow(mtcars)))
{
  bold_flex2 %<>% flextable::bold(i, which.max(mtcars[i,]))
}
bold_flex2

old answer:

library(magrittr)

mtcars %>% 
  flextable::flextable() -> bold_flex

for(i in seq_len(nrow(mtcars)))
{
  bold_flex$body$styles$text$bold$data[i, which.max(mtcars[i,])] <- TRUE
}

enter image description here

To bold the maximum value, I believe you have to do each column separately.

I used two of the columns here and only made the column where the variable is bold.

library(tidyverse)
library(flextable)

data(mtcars)

mtcars %>% 
  flextable() %>%
  bold(~mpg == max(mpg), 1) %>% 
  bold(~drat == max(drat), 5)

enter image description here

Related