Skip to contents

Change the background color of selected rows and columns of a flextable. A function can be used instead of fixed colors.

When bg is a function, it is possible to color cells based on values located in other columns; using hidden columns (those not used by argument colkeys) is a common use case. The argument source must be used to define the columns to be used for the color definition, and the argument j must be used to define where to apply the colors and only accepts values from colkeys.

Usage

bg(x, i = NULL, j = NULL, bg, part = "body", source = j)

Arguments

x

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

i

row selector, see section Row selection with the i parameter in <Selectors in flextable>.

j

column selector, see section Column selection with the j parameter in <Selectors in flextable>.

bg

color to use as background color. If a function, the function must return a character vector of colors.

part

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

source

if bg is a function, source specifies the dataset column to be used as an argument to bg. This is only useful when j is colored with values contained in other columns.

Note

Word does not allow you to apply transparency to table cells or paragraph shading.

Examples

ft_1 <- flextable(head(mtcars))
ft_1 <- bg(ft_1, bg = "wheat", part = "header")
ft_1 <- bg(ft_1, i = ~ qsec < 18, bg = "#EFEFEF", part = "body")
ft_1 <- bg(ft_1, j = "drat", bg = "#606060", part = "all")
ft_1 <- color(ft_1, j = "drat", color = "white", part = "all")
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

if (require("scales")) { ft_2 <- flextable(head(iris)) colourer <- col_numeric( palette = c("wheat", "red"), domain = c(0, 7) ) ft_2 <- bg(ft_2, j = c( "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width" ), bg = colourer, part = "body" ) ft_2 } #> Loading required package: scales

Sepal.Length

Sepal.Width

Petal.Length

Petal.Width

Species

5.1

3.5

1.4

0.2

setosa

4.9

3.0

1.4

0.2

setosa

4.7

3.2

1.3

0.2

setosa

4.6

3.1

1.5

0.2

setosa

5.0

3.6

1.4

0.2

setosa

5.4

3.9

1.7

0.4

setosa