简体   繁体   中英

Conditionals by row with Formattable package in R

I want to know how to assign a conditional format to a table so that each row has a different condition that needs to be fulfilled. So that in statistic row, if the value <0.96 it turns red, and in the case of p-value row if the value is > 0.05 it turns red.

I'm formatting from the following dataframe

df_try
    Normal        Jan        Feb
1  stistic 0.93069466 0.90404849
2 p-values 0.05123532 0.01056474

My condition formatting is in the code imporvement_formatter but naturally, it turns all values red because all are <0.96. I need a second condition for the next row that works for the >0.05 condition

i2 <- df_try %>%
+   select(c(`Normal`,`Jan`, `Feb`))
> formattable(i2)
improvement_formatter <- 
+   formatter("span", 
+             style = x ~ style(
+               font.weight = "bold", 
+               color = ifelse(x < 0.96, customRed, "black")))
> 
> formattable(i2, align =c("l","c","c"), list(
+   `Indicator Name` = 
+     formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
+   `Jan` = improvement_formatter
+ ))

Have a look at the area function. It helps to use formatters on rows and not just on columns. So you can define your formatters like you did and then use them specificly on certain rows and columns. Here is an example:

library(formattable)

df_try <- structure(list(Normal = structure(2:1, .Label = c("p-values", 
                                                            "stistic"), class = "factor"), Jan = c(0.93069466, 0.05123532
                                                            ), Feb = c(0.90404849, 0.01056474)), class = "data.frame", row.names = c("1", 
                                                                                                                                     "2"))

first_col_formatter <- formatter("span", 
                                 style = ~ style(color = "grey",
                                                 font.weight = "bold"))

improvement_formatter <- formatter("span", 
                style = x ~ style(
                font.weight = "bold", 
                color = ifelse(x < 0.96, "red", "black")))

improvement2_formatter <- formatter("span", 
                                   style = x ~ style(
                                     font.weight = "bold", 
                                     color = ifelse(x > 0.05, "red", "black")))

formattable(df_try,
            align =c("l","c","c"),
            list(Normal = first_col_formatter,
              area(row = 1, col = -1) ~ improvement_formatter,
                 area(row = 2, col = -1) ~ improvement2_formatter))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM