library(tidyr)

# Create a data frame in long format
long_data <- data.frame(
  digits = rep(1:5, each = 3),
  category = rep(c("A", "B", "C"), times = 5),
  value = c(10, 20, 30, 15, 25, 35, 12, 22, 32, 18, 28, 38, 14, 24, 34),
  color_code = c("red", "red", "red", "red", "blue", "blue", "blue", "blue", "blue", "green", "green", "green", "green", "green", "green")
)

我有一个长格式的DATA_FRAME,其中每个值都是彩色编码的.我发现通过应用基于COLOR_CODE的条件格式,可以使用Openxlsx库在Excel中对此输出进行 colored颜色 编码.然而,如果我需要最终的Excel输出是宽格式,但仍然是彩色编码的,我想不出该怎么做.

我没能找到解决这个问题的办法.请帮帮忙.

推荐答案

Note:使用此代码,您可以指定更具体的十六进制 colored颜色 值.例如"#00FF00"而不是"Green".

library(purrr)
library(openxlsx)
library(tidyr)

wide <- long_data |>
  pivot_wider(id_cols = digits, names_from = category, values_from = value)

colors <- long_data |>
  pivot_wider(id_cols = digits, names_from = category, values_from = color_code)

color_loc <- map(set_names(unique(long_data$color_code)), ~ as.data.frame(which(colors == .x, arr.ind = TRUE)))
color_style <- imap(color_loc, ~ createStyle(fontColour = .y))

wb <- write.xlsx(wide, "output.xlsx")
iwalk(color_loc, ~ addStyle(wb, 1, color_style[[.y]], rows = .x$row + 1, cols = .x$col))                    
saveWorkbook(wb, "output.xlsx", overwrite = TRUE)
  1. wide是宽格式数据,colors是相同的 struct 化数据,但具有与值相同的单元格级 colored颜色 .
> wide
#   digits     A     B     C
#    <int> <dbl> <dbl> <dbl>
# 1      1    10    20    30
# 2      2    15    25    35
# 3      3    12    22    32
# 4      4    18    28    38
# 5      5    14    24    34

> colors
#   digits A     B     C    
#    <int> <chr> <chr> <chr>
# 1      1 red   red   red  
# 2      2 red   blue  blue 
# 3      3 blue  blue  blue 
# 4      4 green green green
# 5      5 green green green
  1. 对于每种唯一的 colored颜色 ,我们将获得该 colored颜色 的所有单元格的行和列索引位置.因此,如果您更改 colored颜色 、添加 colored颜色 和/或删除 colored颜色 ,此代码将起作用:
> color_loc
# $red
#   row col
# 1   1   2
# 2   2   2
# 3   1   3
# 4   1   4
# 
# $blue
#   row col
# 1   3   2
# 2   2   3
# 3   3   3
# 4   2   4
# 5   3   4
# 
# $green
#   row col
# 1   4   2
# 2   5   2
# 3   4   3
# 4   5   3
# 5   4   4
# 6   5   4
  1. 对于每种 colored颜色 ,我们创建一个工作表样式color_style.
  2. 最后,在创建工作簿对象(wb)之后,我们将Each样式应用于特定的行和列索引(在Excel中使用行+1来说明标题行).

Output

enter image description here

R相关问答推荐

在边界外添加注释或标题

更新合适的R mgcv::bam模型报告无效类型(关闭).'';错误

工作流程_set带有Dplyrr风格的 Select 器,用于 Select 结果和预测因子R

ggplot的轴标签保存在officer中时被剪切

R中插入符号训练函数的中心因子和尺度因子预测

try 将 colored颜色 编码添加到ggploly的标题中

如何基于两个条件从一列中提取行

根据1个变量绘制 colored颜色 发散的 map ,由另一个变量绘制饱和度,ggplot2不工作

将选定的索引范围与阈值进行比较

R -使用矩阵reshape 列表

扩展R中包含列表的数据框

数据集上的R循环和存储模型系数

有毒元素与表观遗传年龄的回归模型

在使用SliderInput In Shiny(R)设置输入数据的子集时,保留一些情节痕迹

使用其他DF中的文件名将列表中的每个元素保存到文件中

了解nchar在列表上的意外行为

如何捕获这个shiny 的、可扩展的react 性用户输入矩阵作为另一个react 性对象,以便进一步操作?

汇总数据:在跨越()all_of()Dynamic_list_of_vars=>;所选内容不能有缺失值的汇总()中出错

在具有条件的循环中添加行

用LOOCV进行K近邻问题