我会用两个部分来解决手头的问题.标题由第1行和第2行组成,主体由从3开始的其余行组成.使用openxlsx2
0.6.1(当前在CRAN传入队列中)重新创建该表,如下所示.
library(openxlsx2)
packageVersion("openxlsx2")
#> [1] '0.6.1'
# table data
data <- data.frame(
X = c("A", "B", "C", "D", "E"),
Y = c(1, 1, 2, 2, 3),
Choice1.a = c(2, 2, 2, 3, 3),
Choice1.b = c(5, 6, 5, 5, 6),
Choice2.a = c(1, 1, 1, 2, 2),
Choice2.b = c(6, 6, 5, 5, 6)
)
# table header
head <- data.frame(
x = c("", "X"),
y = c("", "Y"),
c1_a = c("Choice 1", "a"),
c1_b = c("", "b"),
c2_a = c("Choice 2", "a"),
c2_b = c("", "b")
)
# create a temporary file
tmp <- temp_xlsx()
wb_workbook() %>%
wb_add_worksheet() %>%
# write data without column names
# - header
wb_add_data(x = head, colNames = FALSE) %>%
# - body
wb_add_data(dims = "A3:F8", x = data, colNames = FALSE) %>%
# merge groups
# note: with previous openxlsx2 releases cols needs to be c("C", "D") or 3:4
wb_merge_cells(cols = "C:D", rows = 1) %>%
wb_merge_cells(cols = "E:F", rows = 1) %>%
# style groups
wb_add_cell_style(dims = "C1:F1", horizontal = "center") %>%
# save the output
wb_save(tmp)
# # open file
# xl_open(tmp)