I did not succeed in adding the header row and also I had trouble with printing the row headers ('top class' etc). This is my best result:
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(flextable) # https://ardata-fr.github.io/flextable-book/index.html
library(officer)
df <- data.frame(names= c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", "Hornet Sportabout", "Valiant", "Duster 360", "Merc 240D", "Merc 230", "Merc 280", "Merc 280C", "Merc 450SE", "Merc 450SL", "Merc 450SLC", "Cadillac Fleetwood"),
score = c(21, 21, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17.3, 15.2, 10.4),
cclass= c(rep("class top",3),rep("class medium",3),rep("class lower",3),rep("unknown",6) ) )
table1 <- df %>% rownames_to_column("rank") %>% rename(cartype = names) %>%
mutate(score = format(score,digits=3)) %>%
select(cclass,rank,cartype,score)
ft1 <- flextable::flextable(table1) %>%
border( border = fp_border(width = 2, color = "#007FA6"), part = "all" ) %>%
rotate(j=1,rotation="btlr") %>%
merge_v(j = 1) %>%
set_header_labels(cclass = "", cartype="Car type", rank="#") %>%
autofit(part = "all")
ft1
Created on 2021-07-20 by the reprex package (v2.0.0)
This produces the following table: