使用 openxlsx 包在 R 中的字符列上使用 conditionalFormatting()

问题描述

我正在尝试使用 openxlsx 包从 R 中创建 excel 表输出。在创建输出之前,我需要在我的值上放置两种类型的条件格式。

但是我一直无法完成此操作,因为我将数字作为文本存储在 R 中 - 这是出于报告目的的要求。

这是一个示例代码

library(openxlsx)

tablex <- cbind.data.frame(vec1 = c("120","ug/L","10 ","1.38 ","2.53 ","80.7 ","<5 ","<1 "," <1 ","73.6 ","61.7 J+","43.9 ","43.1 ","<20 ","153 ","131 ","151 ","140 "))
tablex$vec1 <- as.character(tablex$vec1)

### Table 3A ####
tables <- createWorkbook()
addWorksheet(tables,"TableX")
writeData(tables,"TableX",tablex,startCol = 1,startRow = 1,rowNames = FALSE,keepNA = T,na.string = "--")

## conditional formatting styles ###
cond.style1 <- createStyle(bgFill = "grey",fontColour = "#9C0006",halign = "center")
cond.style2 <- createStyle(fontColour = "grey",halign = "center")


## works incorrectly ####
conditionalFormatting(tables,cols = 1,rows = 3:26,rule = ">=$A$2",style = cond.style1)

##does not work! ####
# conditionalFormatting(tables,#                       rows = 3:26,type = "contains",#                       rule = " <",style = cond.style2)

saveWorkbook(tables,file = "./Output/TablesX.xlsx",overwrite = TRUE)


cond.style1 突出显示正确符合规则的值,但也突出显示一些附加值。 '''cond.style2''' 根本不起作用。 R 控制台中没有出现错误,但是当我打开 excel 时,它会出现错误 Replaced Part: /xl/worksheets/sheet1.xml part with XML error. An attribute value must not contain '<'. Line 1,column 2145.

感谢有关此问题的任何帮助。谢谢

解决方法

这是我们可以通过基本上忘记条件格式并将样式单独应用于每个单元格来提出的一个技巧:

tablex <- cbind.data.frame(vec1 = c("120","ug/L","10 ","1.38 ","2.53 ","80.7 ","<5 ","<1 "," <1 ","73.6 ","61.7 J+","43.9 ","43.1 ","<20 ","153 ","131 ","151 ","140 "))
tablex$vec1 <- as.character(tablex$vec1)

### Table 3A ####
tables <- createWorkbook()
addWorksheet(tables,"TableX")
writeData(tables,"TableX",tablex,startCol = 1,startRow = 1,rowNames = FALSE,keepNA = T,na.string = "--")


cond.style1 <- createStyle(bgFill = "grey",fontColour = "#9C0006",halign = "center")
cond.style2 <- createStyle(fontColour = "grey",halign = "center")

 
for(i in 3:nrow(tablex)) {
  # i = 2
  thresh <- as.numeric(tablex$vec1[1])
  cur.val <- tablex$vec1[i]
  cur.val <- extract_numeric(cur.val)
  
  
  if(!is.na(cur.val) & cur.val>= thresh ) {
    addStyle(tables,sheet = 1,cond.style1,rows = (i+1),cols = 1,gridExpand = TRUE)
  } else {
  print(i+1)
    }
  
}


saveWorkbook(tables,file = "./Output/TablesX.xlsx",overwrite = TRUE)