【问题标题】:R Formattable package - Changing Colors by Row Value in Column Containing Character VectorR Formattable 包 - 通过包含字符向量的列中的行值更改颜色
【发布时间】:2017-04-10 10:59:30
【问题描述】:

我有这个 data.frame,我想使用 formattable 包为每个名称分配不同的颜色,其中“Bob”=“Blue”、“Ashley”=“Red”等。有什么想法吗?

我刚开始使用 r 编程,但我在格式化包方面特别苦苦挣扎,因为示例很少,并且文档集中在数值上。

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(48, 47, 40, 28, 29, 29, 27, 27, 31, 30),
  test1_score = c(18.9, 19.5, 19.6, 12.9, 11.1, 7.3, 4.3, 3.9, 2.5, 1.6),
  test2_score = c(9.1, 9.1, 9.2, 11.1, 13.9, 14.5, 19.2, 19.3, 19.1, 18.8),
  stringsAsFactors = FALSE)

到目前为止,我只有一个价值,但其余的都在苦苦挣扎:

  name = formatter("span", style = x ~ ifelse(x == "Bob", 
        style("background-color" = "blue", display = "block", "border-radius" = "4px", font.weight = "bold"), NA))))

我如何从该列添加其他参数,就像您可以在 DT 包中使用 formatStyle 一样。

%>%
  formatStyle(
    'name',
    backgroundColor = styleEqual(c('Bob', 'Ashley'), c('blue', 'red'))

【问题讨论】:

    标签: r colors formattable


    【解决方案1】:

    您可以使用formatStyle() 中的参数target = 'row' 设置整行而不是单个单元格的样式。

    这是 .Rmd 代码块:

    ```{r data}
    library(formattable)
    library(DT)
    df <- data.frame(
      id = 1:10,
      name = c("Bob", "Ashley", "James", "David", "Jenny", 
               "Hans", "Leo", "John", "Emily", "Lee"), 
      age = c(48, 47, 40, 28, 29, 29, 27, 27, 31, 30),
      test1_score = c(18.9, 19.5, 19.6, 12.9, 11.1, 7.3, 4.3, 3.9, 2.5, 1.6),
      test2_score = c(9.1, 9.1, 9.2, 11.1, 13.9, 14.5, 19.2, 19.3, 19.1, 18.8),
      stringsAsFactors = FALSE)
    datatable(df) %>% formatStyle(
      'name',
      target = 'row',
      backgroundColor = styleEqual(c("Bob", "Ashley"), c('blue', 'red'))
    )
    ```
    

    表格如下所示:

    【讨论】:

      猜你喜欢
      • 2015-05-17
      • 2016-12-08
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多