【问题标题】:How To Reorder Sheet With R如何使用 R 重新排序工作表
【发布时间】:2022-01-16 04:16:53
【问题描述】:

我正在使用 32 张的 Excel 工作簿。但是,当我尝试使用工作表顺序将工作表 32 放在工作簿中工作表 1 的前面时,会出现错误。请在下面找到错误。

worksheetOrder(wb)<-c(32,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)

enter image description here

【问题讨论】:

  • 请为问题提供更多上下文和框架。 openxlsx::worksheetOrder 的文档指出:“此函数不会重新排序工作簿对象中的工作表,它只是在写入文件时打乱顺序。”因此,查看构建工作簿的代码以及使用 32 张工作表保存工作簿的代码会很有帮助。

标签: r openxlsx


【解决方案1】:

这是一个使用 readxl 包的解决方案,但首先让我们创建一个包含 4 张工作表的测试数据集。

data <- list(head(iris), head(mtcars), head(cars), head(airquality))
writexl::write_xlsx(data, 'test.xlsx')

现在,在您的工作目录中,您应该有一个包含 4 张工作表的 excel 文件。第一张有iris 数据集,第二张有mtcars,第三张有cars 和第四张airquality

解决方案 -

library(readxl)

#Order in which you want the sheets to be in
req_order <- c(4, 2, 3, 1)
#Read the sheet names
sheets <- excel_sheets('test.xlsx')
#Read the data in a list
read_data <- lapply(sheets, function(x) read_xlsx('test.xlsx', x))
#Rearrange the data as per `req_order`
read_data <- read_data[req_order]
#Write the data to a new file with the new order. 
writexl::write_xlsx(read_data, 'new_test.xlsx')

您现在可以找到一个包含 4 张工作表的新 Excel 工作簿,其中的顺序已更改为 req_order 中提到的 airqualitymtcarscarsiris

【讨论】:

  • 我不想创建新的工作表,我想重新排序同一个工作表。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
相关资源
最近更新 更多