假设您在 R 中的空格是 NA ,那么以下代码行会有所帮助。代码中的注释以在需要时进行解释。
library(openxlsx)
# find empty columns
columns_to_format <- which(sapply(df1, function(x) length(x) == sum(is.na(x)) ))
rows <- nrow(df1) + 1
wb <- createWorkbook()
# create style used for high lighting empty columns
highlight_cells <- createStyle(fgFill = "yellow")
# Add worksheet
addWorksheet(wb, "example")
writeData(wb, "example", x = df1)
# loop over columns to high light
for(i in seq_along(columns_to_format)) {
addStyle(wb, "example", style = highlight_cells, rows = 2:rows, cols = columns_to_format[i])
}
saveWorkbook(wb, "Example.xlsx", overwrite = TRUE)
数据:
df1 <- structure(list(sample1 = c("yes", "yes", "yes", "yes"), sample2 = c(NA_character_,
NA_character_, NA_character_, NA_character_), sample3 = c("yes",
NA, NA, "yes"), sample4 = c(NA_character_, NA_character_, NA_character_,
NA_character_)), row.names = c(NA, -4L), class = "data.frame")