Openxlsx column width setting using pmax() and apply() when “auto” truncates (#rstats)

I use the R package openxlsx, by Sydney’s Alexander Walker,  a few times per week. When professional stakeholders love Microsoft Excel, we give them the .XLSX workbooks that they seek.

Using setColWidths (..., widths = "auto")usually works to widen columns based on the values present in the workbook. However, I experienced earlier today a failure of this auto-widening feature. I unfortunately cannot provide the confidential data and failed to generate a reproducible example, however, TLDR: The Figure 5 code in the gist below shows how to use the pmax function to identify the maximum of the header length and body text length, per column.

This is an expounding on my StackOverflow answer here, to which I invite you to respond.

Note: The R code is assembled together as a Gist at the bottom of this post.

Openxlsx will often save an Excel workbook without any width adjustments needed.

Here is the starwars data found in Hadley Wickham’s tidyverse collection of packages.

Figure 1


Looks okay, but columns like E (skin_color) show a truncated header.

We can use widths = “auto” in the setColWidths function to auto-widen the column based on the data. I know of no negatives to doing so and therefore always include this code.

Figure 2


We see that widths = “auto” in the setColWidths function serves us well. All of the column headers can be fully-seen and the same is true for the values in the body. The truncation at the far-right is due to my imperfect screenshotting.

I was hoping to reproduce the problem I experienced earlier by trying the storms dataframe. I am including Figure 3 to further emphasize the power of the openxlsx package (using widths = “auto”) and possibly invite exploration of this “subset of the NOAA Atlantic hurricane database best track data“, which also comes with the tidyverse.

Figure 3


Two-row headers might be valuable for those accustomed to Excel pivot tables. This shows a use of mergecells to create a header for the data frame’s column headers. No problem seen with widths = “auto”.

Figure 4


However, I solved my problem with confidential data with the code associated with figure 5, and it looks a bit better than Figure 4. The height column now has no extraneous space, for example. Depending on your font size and features, you might adjust the width_adjuster object (e.g., increase the number for more space).

Figure 5


R code


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s