我需要对一个特定的列进行 colored颜色 条件格式化,将其格式化为百分比,然后将文件导出为.xlsx.请注意,我将使用5个数据框运行此规则代码,并将它们编译成不同工作表中的1个工作簿.如果我在其中设置了百分比,我似乎无法设置条件规则.反之亦然,如果我先设置条件格式,我不确定如何设置该列的百分比格式.请参考下面我的代码.

## Dataframe
cost_table <- read.table(text = "FRUIT  COST  SUPPLY_RATE
1  APPLE   15   0.026377
2  ORANGE   14  0.01122
3  KIWI   13  0.004122
5  BANANA   11  0.017452
6  AVOCADO   10   0.008324       "  , header = TRUE)

## This is the line where I label the %. However if I do that, conditional formatting will not recognize it in the rule
cost_table$SUPPLY_RATE <- label_percent(accuracy = 0.01)(cost_table$SUPPLY_RATE)

## Creating workbook and sheet
Fruits_Table <- createWorkbook()
addWorksheet(Fruits_Table,"List 1")

writeData(Fruits_Table,"List 1",cost_table)


## Style color for conditional formatting
posStyle <- createStyle(fontColour = "#006100", bgFill = "#C6EFCE")
negStyle <- createStyle(fontColour = "#9C0006", bgFill = "#FFC7CE")

## If Supply rate is above 1.5%, it will be green, if it's equivalent or below, it will be red
conditionalFormatting(Fruits_Table, "List 1",
                      cols = 3,
                      rows = 2:6, rule = "C2> 0.015", style = posStyle
)

conditionalFormatting(Fruits_Table, "List 1",
                      cols = 3,
                      rows = 2:6, rule = "C2<= 0.015", style = negStyle
)

输出应如下所示.

Output

推荐答案

你不需要使用scales包中的label_percent.

以下是我使用的代码:

Fruits_Table <- createWorkbook()
addWorksheet(Fruits_Table,"List 1")
writeData(Fruits_Table,"List 1",cost_table)
conditionalFormatting(Fruits_Table, "List 1",
                      cols = 3,
                      rows = 2:6, rule = "> 0.015", style = posStyle) 
conditionalFormatting(Fruits_Table, "List 1",
                       cols = 3,
                        rows = 2:6, rule = "<= 0.015", 
                       style = negStyle)
percent_style <- createStyle(numFmt = "PERCENTAGE")
addStyle(Fruits_Table,"List 1", style = ,percent_style, rows = 2:6, cols = 3)

我试过那个代码,它很管用.

saveWorkbook(Fruits_Table, "my_fruits_table.xlsx", )

enter image description here

Updated to add borderline info

如果您想创建带有百分比格式的边界线,可以使用borderborderStyle,如下所示:


percent_border_style<- createStyle(numFmt = "PERCENTAGE", border = "TopBottomLeftRight", borderStyle = "medium" )
addStyle(Fruits_Table,"List 1", style = ,percent_border_style, rows = 2:6, cols = 3)
saveWorkbook(Fruits_Table, "borderline_fruits_table.xlsx", )

以下是临界结果

enter image description here

R相关问答推荐

如何从使用lapply()的r中的拆分数据帧中删除多个部分?

收件箱摘要表布局在第一列上显示子类别

替换字符的所有实例,但仅限于匹配字符串中

如何计算新变量中的通货inflating 率?

从字符载体创建函数参数

分组时间连续值

将Multilinetring合并到一个线串中,使用sf生成规则间隔的点

如何在emmeans中计算连续变量的对比度

S用事件解决物质平衡问题

条形图和在Ploly中悬停的问题

根据列A中的差异变异列,其中行由列B中的相对值标识

在ggplot2的框图中绘制所有级别的系数

有没有办法使用ggText,<;Sub>;&;<;sup>;将上标和下标添加到同一元素?

如何根据R中其他变量的类别汇总值?

在另一个包中设置断点&S R函数

如何在PDF格式的kableExtra表格中显示管道字符?

自动STAT_SUMMARY统计与手动标准误差之间的差异

我需要使用ggplot2制作堆叠条形图

如何在Quarto中使用美人鱼图表中的标记来加粗文本

需要一个函数来在第一行创建一个新变量,然后用新变量替换一个不同的变量(对于多行)