我有一个数据框,大概是这样的:

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),
                   Choice3.b = c(6,6,5,5,6))

I would like to save it to an excel file so that it looks something like this: enter image description here

有人知道这是否可能吗?

如果不是,我会满足于仅仅改变".EXCEL文件中的分隔符为"".

推荐答案

我会用两个部分来解决手头的问题.标题由第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)

R相关问答推荐

如何判断R中一列的值是否在所有其他列中重复?

如何将多个数据帧附加到R中的多个相应的CSV文件中?

在数据表中呈现数学符号

警告:lmdif:info = 0. nls. lm()函数的输入参数不正确

当两个图层映射到相同的美学时,隐藏一个图层的图例值

使用strsplit()将向量操作为数据框

如何在geom_col中反转条

使用外部文件分配变量名及其值

根据元素和前一个值之间的差值过滤矩阵的元素

在rpart. plot或fancyRpartPlot中使用带有下标的希腊字母作为标签?

在R中按行按列范围查找最大值的名称

用R ggplot2求上、下三角形中两个变量的矩阵热图

为左表中的所有行使用值Fill滚动左连接

R中Gamma回归模型均方误差的两种计算方法不一致

如何将一个方阵分解成没有循环的立方体

如何预测原始数据集并将值添加到原始数据集中

数据集上的R循环和存储模型系数

如何在内联代码中添加额外的空格(R Markdown)

使用函数从R中的列中删除标高

使用一个标签共享多个组图图例符号