Ex-8-1: Make tables with flextable
1 Exercise 1
Dataset: mtcars
- Load the
mtcars
dataset into R. - Use the
flextable
package to create a table that displays the first 10 rows of the dataset formpg
,cyl
,disp
, andhp
. - Apply styles to the table to make
- the texts in the header bold using
bold()
- the texts of the
cyl
column center-aligned including thecyl
in the header usingalign()
- the texts of the
hp
column colored red usingcolor()
- the font size of the texts of the
mpg
18 if the value ofdisp
is greater than 200 usingfontsize()
.
- the texts in the header bold using
Here is the finished table you are trying to make:
Code
# Create a simple flextable
<-
ft flextable(
1:10, ],
mtcars[col_keys = c("mpg", "cyl", "disp", "hp")
%>%
) bold(part = "header") %>%
align(j = 2, align = "center", part = "all") %>%
color(j = 4, color = "red")
2 Exercise 2
Dataset: iris
- Load the
iris
dataset. - Create a
flextable
that displays the first 10 rows of the dataset. - Apply conditional formatting:
- Change the background color of the cells in the
Sepal.Length
column where their values are greater than 5.0 in blue usingcolor
usingbg()
. - Draw orange borders at the bottom of the cells in the
Sepal.Width
column if their values are less than 3.0 usingborder()
. - Draw red borders at both sides of the cells in the
Sepal.Width
column if their corresponding values ofPetal.Width
are less than 1.5 usingborder()
.
- Change the background color of the cells in the
Here is the finished table you are trying to make:
Code
# Create flextable for first 10 rows
<-
ft flextable(iris[1:10,]) %>%
# Apply conditional formatting to Sepal.Length column
bg(i = ~ Sepal.Length > 5, j = "Sepal.Length", bg = "blue") %>%
border(i = ~ Sepal.Width > 3, j = ~ Sepal.Width, border.bottom = officer::fp_border(color = "orange"))
3 Exercise 3: Merging and Grouping Columns
Dataset: airquality
- Load the
airquality
dataset and filter the data so that you have only the first 10 days of May and June. - Create a flextable using selected columns:
Month
,Day
,Ozone
,Wind
. - Group the table by the
Month
column and merge the cells of theMonth
column usingmerge_v()
. - Draw a black border to separate May and June observations
- Draw a black line at the bottom of the table which was somehow lost in step 3 using
fix_border_issues()
. - Add a caption to the table using
set_caption()
.
Here is the finished table you are trying to make:
Code
# Select columns
<-
ft %>%
airquality ::filter(Month %in% c(5, 6) & Day <= 10) %>%
dplyrc("Month", "Day", "Ozone", "Wind")] %>%
.[, # Create flextable
flextable() %>%
# Merge Month column
merge_v(j = "Month") %>%
border(i = 10, border.bottom = officer::fp_border(color = "black")) %>%
fix_border_issues() %>%
# Add a caption
set_caption("Airquality Data Table with Grouped Month")