如何使用 as_grouped_data 格式在具有相同值的相同单元格的弹性表中着色

问题描述 投票:0回答:1

我有这个数据集,在使用

as_grouped_data(., groups = "")
函数后,我尝试使用相同的颜色、具有相同值的单元格进行着色。

dat <- data.frame(
  stringsAsFactors = FALSE,
  A = c("NHH","NHH","NHH","NHH",
        "NHH","NHH","NHH","NHH","NHH","cUU","cUU","cUU",
        "cUU","cUU","cUU","cUU","cUU","cUU","cUU","cUU","cUU",
        "cUU","cUU","cUU","cUU","cUU","cUU","cUU"),
  B = c("uJc","GBY","rYv","hYl",
        "hat","hqL","jxF","hqL","VMg","gWX","Vae","uJc",
        "GBY","Vae","hYl","uJc","pEI","gWX","ZCY","ZCY","Vae",
        "Vae","rYQ","veT","hqL","Vae","hYl","QIN")
)%>% as_grouped_data(., groups = "A")


cid <- dplyr::consecutive_id(dat$B)
cols <- sample(colors(), size = length(unique(cid)))
mycolors <- cols[cid]


flextable(dat) |> 
  bg(i = 1:nrow(dat), j = 'B', bg = mycolors, part = 'body')

我注意到生成的颜色是随机选择的,因此有一些像黑色和类似的颜色太暗而无法为细胞着色。有可能以某种方式解决这个问题吗?

r colors cell flextable
1个回答
1
投票

如果没有可重现的示例,就很难提供帮助。我只会使用您的数据和第一列来演示:

dat <- data.frame(
  stringsAsFactors = FALSE,
                 A = c("NHH","NHH","NHH","NHH",
                       "NHH","NHH","NHH","NHH","NHH","cUU","cUU","cUU",
                       "cUU","cUU","cUU","cUU","cUU","cUU","cUU","cUU","cUU",
                       "cUU","cUU","cUU","cUU","cUU","cUU","cUU"),
                 B = c("uJc","GBY","rYv","hYl",
                       "hat","hqL","jxF","hqL","VMg","gWX","Vae","uJc",
                       "GBY","Vae","hYl","uJc","pEI","gWX","ZCY","ZCY","Vae",
                       "Vae","rYQ","veT","hqL","Vae","hYl","QIN")
)

cid <- dplyr::consecutive_id(dat$A)
cols <- sample(colors(), size = length(unique(cid)))
mycolors <- cols[cid]
  
  
flextable(dat) |> 
  bg(bg = mycolors)

© www.soinside.com 2019 - 2024. All rights reserved.