问题描述
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,44.35,44.4,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()
函数。
有必要突出显示行 Change 和 Change % 中的单元格,如果为正值,则为绿色,如果为负值,则为红色。我发现了一个类似的函数 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,44.35,44.4,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))