如何根据条件突出显示 table 中的特定行值

How highlight specific row values in a table based on a condition

我有一个数据框

structure(list(date = c("4/12/2021", "4/13/2021", "4/14/2021", 
"4/15/2021", "4/16/2021", "4/17/2021", "4/18/2021", "Change", 
"Change (%)"), price1= c(44.42, 43.77, 
43.77, 44.35, 44.4, NA, NA, 0.609999999999999, 1.40126803271157
), price2= c(40.68, 41.73, 45.22, 47.68, 47.35, 44.33, 43.34, 
14.6685714285714, 49.4485913797255)), row.names = c("8", "9", 
"10", "11", "12", "13", "14", "1", "15"), class = "data.frame")

我正在尝试使用 formattable 包和 formattable() 函数。 如果正值,则有必要用绿色突出显示更改和更改 % 行中的单元格,如果为负值,则用红色突出显示。我发现了一个类似的函数 here,但它只适用于列( `2015`= color_tile(customGreen, customGreen0) 部分)

你能帮忙找到解决方法吗?

看看 area 函数。您可以在 row 参数中指定用于着色的行索引。如果您对整行着色不感兴趣(只是某些列的行),您可以在 col 参数中定义这些列。

数据

df <- structure(list(date = c("4/12/2021", "4/13/2021", "4/14/2021", 
                        "4/15/2021", "4/16/2021", "4/17/2021", "4/18/2021", "Change", 
                        "Change (%)"), price1= c(44.42, 43.77, 
                                                 43.77, 44.35, 44.4, NA, NA, 0.609999999999999, 1.40126803271157
                        ), price2= c(40.68, 41.73, 45.22, 47.68, 47.35, 44.33, 43.34, 
                                     14.6685714285714, 49.4485913797255)), row.names = c("8", "9", 
                                                                                         "10", "11", "12", "13", "14", "1", "15"), class = "data.frame")

代码

library(formattable)

# define row indices
row_change <- which(df$date == "Change")
row_change_percent <- which(df$date == "Change (%)")

# define coloring
red_green_formatter <- formatter("span", 
                                 style = x ~ style(
                                  display = "block",
                                `background-color` = ifelse(x < 0, "red", 
                                                ifelse(x > 0, "lightgreen", "white"))))

# set formattable and define coloring for rows 8 and 9 for every column but not the first
formattable(df,
            list(area(row = row_change:row_change_percent,
                      col = -1) ~ red_green_formatter))