Skip to contents

Compute and apply the minimum widths and heights needed to display each cell's content on a single line, with an optional extra margin (add_w, add_h).

This function sizes columns to fit their content. It does not constrain the table to a given total width. To enforce a maximum width, use fit_columns() (wraps text) or fit_to_width() (shrinks font size).

Note that this function is not related to 'Microsoft Word' Autofit feature.

There is an alternative to fixed-width layouts that works well with HTML and Word output that can be set with set_table_properties(layout = "autofit"), see set_table_properties().

Usage

autofit(
  x,
  add_w = 0.1,
  add_h = 0.1,
  part = c("body", "header"),
  unit = "in",
  hspans = "none"
)

Arguments

x

a 'flextable' object, see flextable-package to learn how to create 'flextable' object.

add_w

extra width to add in inches

add_h

extra height to add in inches

part

part selector, see section Part selection with the part parameter in <Selectors in flextable>. Value 'all' can be used.

unit

unit for add_h and add_w, one of "in", "cm", "mm".

hspans

specifies how cells that are horizontally are included in the calculation. It must be one of the following values "none", "divided" or "included". If "none", widths of horizontally spanned cells is set to 0 (then do not affect the widths); if "divided", widths of horizontally spanned cells is divided by the number of spanned cells; if "included", all widths (included horizontally spanned cells) will be used in the calculation.

Examples

ft_1 <- flextable(head(mtcars))
ft_1

mpg

cyl

disp

hp

drat

wt

qsec

vs

am

gear

carb

21.0

6

160

110

3.90

2.620

16.46

0

1

4

4

21.0

6

160

110

3.90

2.875

17.02

0

1

4

4

22.8

4

108

93

3.85

2.320

18.61

1

1

4

1

21.4

6

258

110

3.08

3.215

19.44

1

0

3

1

18.7

8

360

175

3.15

3.440

17.02

0

0

3

2

18.1

6

225

105

2.76

3.460

20.22

1

0

3

1

ft_2 <- autofit(ft_1) ft_2

mpg

cyl

disp

hp

drat

wt

qsec

vs

am

gear

carb

21.0

6

160

110

3.90

2.620

16.46

0

1

4

4

21.0

6

160

110

3.90

2.875

17.02

0

1

4

4

22.8

4

108

93

3.85

2.320

18.61

1

1

4

1

21.4

6

258

110

3.08

3.215

19.44

1

0

3

1

18.7

8

360

175

3.15

3.440

17.02

0

0

3

2

18.1

6

225

105

2.76

3.460

20.22

1

0

3

1