如何根据R中的条件更改整个表格的字体颜色?

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

我想根据整个表格的条件更改所有值字体颜色。参考表如下


`Category Name`      Oct     Nov     Dec   Jan    Feb   Mar    Apr      May    Jun     Jul     Aug
   <fct>              <dbl>   <dbl>   <dbl> <dbl>  <dbl> <dbl>  <dbl>    <dbl>  <dbl>   <dbl>   <dbl>
 1 Diet Soda          6.05    -5.05   8.70   32.4 -11.0  -26.8   3.19    0.336  -2.62   -3.91   -7.04
 2 Soda              -8.45   -17.6    0.602  16.5 -14.9  -22.8  15.1     9.75   18.1    28.3    32.2 
 3 Sparkling Beve~    9.85     6.58  23.1    42.3   6.43 -15.3  16.6     6.61    6.31    8.53    2.46
 4 Energy            30.4     29.1   60.1    91.3  41.4   20.1  67.6    61.2    56.9    56.4    56.4 
 5 Tea              -18.9    -25.4   -2.93   15.2 -17.3  -26.8   9.75    1.28   -2.45   -4.73    4.42
 6 Water            -10.5    -24.5   -5.66   20.8 -17.5  -33.1   7.43   -5.08   10.6     6.11   -1.01
 7 Rtd Coffee        -8.65   -11.9    2.63   14.3 -17.5  -32.7  -4.51   -6.31  -15.5     4.56   11.5 
 8 Vitamin Enhanc~   36.6     35.2   63.0   110.   53.0   24.7  79.3    64.7    49.7    36.8    34.7 
 9 New Age Bevera~  -17.5    -16.9   -6.23   12.9 -14.5  -27.2 -16.5   -21.1   -37.0   -33.9   -25.2 
10 Hydration / Sp~    8.71     1.15  18.2    50.1   9.39 -12.4  46.6    45.5    32.7    43.8    40.5 
11 Juice             -0.414    2.89  45.6    65.3   5    -11.6  16.6    22.2    15.4    29.2    16.4 
12 Flavored Nonca~   65.2     69.1   89.0   114.   78.1   63.4 123.     86.4    85.0    33.8    22.8 
13 Soda Can        -100     -100    NaN     NaN   NaN    NaN   NaN    -100     NaN     NaN     NaN   
14 Milk              NA       NA     NA      NA    NA     NA    NA      NA      NA    1250    1114.  
15 Diet Soda Can     NA     -100     NA      NA    NA     NA    NA      NA      NA     -75      NA   
16 Probiotic Beve~  NaN      NaN     NA      NA    NA     NA    NA      NA      NA      NA      NA   
# ... with 1 more variable: Sep <dbl>

我想将所有-值设置为红色,将所有+值设置为绿色。我尝试设置一个全局变量以在formattable表中调用,但它不起作用。参考代码如下:

formatter_bev <- 
  formatter("span", 
            style = x ~ style(
              font.weight = "bold", 
              color = ifelse(x > 0, "green", ifelse(x < 0, "red"))))


bev_percent_plt <- formattable(Bev_Percent_change_table, align =c("l","c","c","c","c", "c", "c", "c", "c", "c", "c", "r"), list(
  `Indicator Name` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), formatter_bev(col=2:13)))

任何帮助将不胜感激!

r colors dplyr formattable
1个回答
0
投票

您差点就吃了。代替“ formatter_bev(col = 2:13)”,要更改一列,您应该编写:

oct = formatter_bev

要更改多个,这是一个'区域',因此您需要:

area(col = 2:13) ~ formatter_bev

在这里找到:https://cran.r-project.org/web/packages/formattable/vignettes/formattable-data-frame.html

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