带有 openxlsx 包的 R 字符列上的 conditionalFormatting()

conditionalFormatting() on a character column in R with openxlsx package

我正在尝试使用 openxlsx 包在 R 中创建 excel table 输出。在创建输出之前,我需要对我的值进行两种类型的条件格式设置。

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

这是一个示例代码:

library(openxlsx)

tablex <- cbind.data.frame(vec1 = c("120","ug/L","10 ","1.38 ","2.53 ","80.7 ","<5 ","<1 ",
                                    "<1 "," <1 ","<1 ","<1 ","<1 ","<1 ","<1 ","73.6 ","61.7 J+","43.9 ",
                                    "43.1 ","<20 ","<5 ","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, "TableX",cols = 1,
                      rows = 3:26,
                      rule = ">=$A", style = cond.style1)

##does not work! ####
# conditionalFormatting(tables, "TableX", cols = 1,
#                       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 "," <1 ","<1 ","<1 ","<1 ","<1 ","<1 ","73.6 ","61.7 J+","43.9 ",
                                    "43.1 ","<20 ","<5 ","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)