【问题标题】:Conditionals by row with Formattable package in R使用 R 中的 Formattable 包按行排列条件
【发布时间】:2020-09-25 16:39:08
【问题描述】:

我想知道如何为表格分配条件格式,以便每一行都有需要满足的不同条件。因此,在统计行中,如果值 0.05 则变为红色。

我正在从以下数据框格式化

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

我的条件格式在代码 imporvement_formatter 中,但很自然,它会将所有值变为红色,因为所有值均 0.05 条件

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
+ ))

【问题讨论】:

    标签: r conditional-formatting formattable


    【解决方案1】:

    看看area 函数。它有助于在行上使用格式化程序,而不仅仅是在列上。因此,您可以像以前一样定义格式化程序,然后专门在某些行和列上使用它们。这是一个例子:

    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))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多