有several great R packages for reading and writing MS Excel spreadsheets。从R is easy to LaTeX tables导出上标(另请参阅this),但有没有办法直接将上标从R导出到Excel表格?
一个例子:
library(openxlsx)
dt <- data.frame(a = 1:3, b = c("a", "b", ""))
dt$try1 <- paste0(dt$a, "^{", dt$b, "}") ## Base R, openxlsx does not seem to know how to handle expression()
dt$try2 <- paste0(dt$a, "\\textsuperscript{", dt$b, "}") # Should work in xtable
dt$try3 <- paste0("\\textsuperscript{", dt$b, "}") # This does not work either
write.xlsx(dt, "Superscript test.xlsx")
代码生成一个漂亮的Excel表,但不处理LaTeX代码(可以理解,因为我们导出到Excel)。也许有一个Excel的上标代码可以绕过这个问题?
答案 0 :(得分:1)
这个问题已经存在了一段时间,我想OP已经找到了解决方案。无论如何,我的解决方案完全基于this open git issue。
要执行此操作,您需要定义上标符号并创建一个单独的列,就像在dt1$try1
中所做的一样。在示例中,我将上标字符括在_[]
中。只是要避免在工作簿的其他情况下可能会发现歧义。
dt <- data.frame(a = 1:3, b = c("a", "b", ""))
dt$sup <- paste0(dt$a, "_[", dt$b, "]") # create superscript col, enclosed in '_[]'
wb <- openxlsx::createWorkbook() # create workbook
openxlsx::addWorksheet(wb, sheetName = "data") # add sheet
openxlsx::writeData(wb, sheet=1, x=dt, xy=c(1, 1)) # write data on workbook
for(i in grep("\\_\\[([A-z0-9\\s]*)\\]", wb$sharedStrings)){
# if empty string in superscript notation, then just remove the superscript notation
if(grepl("\\_\\[\\]", wb$sharedStrings[[i]])){
wb$sharedStrings[[i]] <- gsub("\\_\\[\\]", "", wb$sharedStrings[[i]])
next # skip to next iteration
}
# insert additioanl formating in shared string
wb$sharedStrings[[i]] <- gsub("<si>", "<si><r>", gsub("</si>", "</r></si>", wb$sharedStrings[[i]]))
# find the "_[...]" pattern, remove brackets and udnerline and enclose the text with superscript format
wb$sharedStrings[[i]] <- gsub("\\_\\[([A-z0-9\\s]*)\\]", "</t></r><r><rPr><vertAlign val=\"superscript\"/></rPr><t xml:space=\"preserve\">\\1</t></r><r><t xml:space=\"preserve\">", wb$sharedStrings[[i]])
}
openxlsx::saveWorkbook(wb, file="test.xlsx", overwrite = TRUE)
wb$sharedStrings
包含工作簿单元格中字符串的唯一实例。选择的模式将捕获_[]
中包含的单词,数字和空格(或空字符串)的任何实例。循环的第一部分检查上标表示法中是否缺少字符,如果为TRUE
,则会删除该表示法。