R语言 使用OpenXLSX进行条件注解

polhcujo  于 2023-06-19  发布在  其他
关注(0)|答案(2)|浏览(97)

我想使用R中的OpenXLSX在一个单元格上添加一个注解,只有当满足某些条件时(单元格不是空的,不同的列包含特定的文本)。不确定这是否可能。
当然,我可以有条件地应用基于以下条件的样式:

Name<- c("Bob", "Fred", "Smith", "Henry", "Joe")
Other<- 1:5
df<- data.frame(Name, Other)

wb <- createWorkbook()
addWorksheet(wb, "Names")
writeData(wb, 1, df, startRow = 1, startCol=1, colNames = F)

West<- createStyle(bgFill = "#DCE6F1")
conditionalFormatting(wb, 1, cols = 2, rows = 1:5, rule = 'AND($A1 == "Smith", $B1<>"")', style = West)

但是,正如预期的那样,尝试将其与writeComment结合使用只会返回一个错误,即style必须是Style对象:

conditionalFormatting(wb, 1, col = 2, rows = 1:5, rule = 'AND($A1 == "Smith", $B1<>"")', style = writeComment(wb, 1, col = "B", row = which(df$Name == "Smith"), comment = createComment(comment = "Test Comment")))

有什么办法可以做到这一点吗?

vpfxa7rd

vpfxa7rd1#

您可以通过在openxlsx函数外确定符合注解com_row的行来实现这一点;然后在writeComment函数中使用com_row

library(openxlsx)

Name<- c("Bob", "Fred", "Smith", "Henry", "Joe")
Other<- 1:5
df<- data.frame(Name, Other)

wb <- createWorkbook()
addWorksheet(wb, "Names")
writeData(wb, 1, df, startRow = 1, startCol=1, colNames = F)

West<- createStyle(bgFill = "#DCE6F1")
conditionalFormatting(wb, 1, cols = 2, rows = 1:5, rule = 'AND($A1 == "Smith", $B1<>"")', style = West)

com1 <- createComment(comment = "Test Comment")
com_row <- which(df$Name == "Smith" & df$Other != "")

# wrap `writeComment` function in an if statement to deal with case 
# where there are no names = "Smith" and NAs in Other. This does away
# with the case where `which` evaluates to `integer(0)` when there
# are no elements which are indexed.

if(length(com_row) > 0){
  
  writeComment(wb, 1, col = 2, row = com_row, comment = com1)
  
}

saveWorkbook(wb, file = "condition_and_comment_eg.xlsx", overwrite = TRUE)

其结果是:

创建于2023-06-07,使用reprex v2.0.2

  • 测试数据框 *

对于没有行满足条件的情况。

Name<- c("Bob", "Fred", "Noname", "Henry", "Joe")
Other<- c(1:2, NA_real_, 4:5)

没有满足条件的行的数据框的工作簿输出:

oprakyz7

oprakyz72#

我的方法与Peters类似,只使用openxlsx2,而不使用条件格式。

library(openxlsx2)
Name <- c("Bob", "Fred", "Smith", "Henry", "Joe", "Smith", "Joe", "Smith")
Other <- c(1:5, NA, 7:8)
df <- data.frame(Name, Other)

# prepare the workbook
wb <- wb_workbook()$add_worksheet()$add_data(x = df, na.strings = NULL)

# get the required cell information
data <- wb_data(wb)
rows <- rownames(data[data$Name == "Smith" & !is.na(data$Other) & data$Other != "",])

for (row in rows) {
  
  dim <- attr(data, "dims")[row, "B"]
  c1 <- create_comment("this is a comment", "")
  
  wb$add_fill(dims = dim, color = wb_color("yellow"))
  wb$add_comment(dims = dim, comment = c1)
  
}

if (interactive()) wb$open()

相关问题