79689272

Date: 2025-07-03 17:47:49
Score: 0.5
Natty:
Report link

"I want to maintain a consistent column width when possible" & "Method to set minimum column width in flextable"

You can use strwidth in this case for Arial point 11, and measure the maximum text width, if it's below your desiredWidth, set it to desiredWidth using pmax() + width

library(flextable)
library(magrittr)

### Ex. Tbls
vendor <- data.frame("Vendor" = rep("A longer Company Name", 4),   "Sales" = c(20,30,12,32))

autosize_min_width <- function(
    dd,    # dataframe
    desWid # desired Widths
)
{
  flextable(dd)|>
    width(width = pmax(sapply(seq_along(names(dd)), \(i) max(strwidth(dd[,i], font = 11, units = 'in'))), desWid))
}

desiredWidths <- c(.5,.5)
autosize_min_width(vendor, desiredWidths)

giving what you want:

out

Whereas your code

flextable(vendor) %>%
  autofit() %>% 
  width(j = which(dim(.)$widths < desiredWidths), desiredWidths[which(dim(.)$widths < desiredWidths)])

gives

out2

which I guess is not what you want?

Reasons:
  • Whitelisted phrase (-1.5): You can use
  • RegEx Blacklisted phrase (1): I want
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-1):
Posted by: Tim G