Search code examples
rflextable

Bold the maximum value in each row


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.


Solution

  • 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