【问题标题】:Formatting data in a table as percentage将表格中的数据格式化为百分比
【发布时间】:2020-08-17 21:55:37
【问题描述】:

我有一个如下所示的数据框:

这是创建这个 DF 的代码:

structure(list(ethnicity = structure(c(1L, 2L, 3L, 5L), .Label = c("AS", 
"BL", "HI", "Others", "WH", "Total"), class = "factor"), `Strongly agree` = c(30.7, 
26.2, 37.4, 31.6), Agree = c(43.9, 34.5, 41, 45.4), `Neither agree nor disagree` = c(9.4, 
14.3, 8.6, 8.7), Disagree = c(10, 15.5, 9.9, 9.7), `Strongly disagree` = c(6, 
9.5, 3.2, 4.6)), row.names = c(NA, -4L), class = "data.frame")

我想添加数据条并将这些数字设为百分比。我尝试使用 formattable 库来做到这一点(请参阅下面的代码)。

formattable(df,align=c("l","l","l","l","l","l"),
        list(`ethnicity` = formatter("span", style = ~ style(color = "grey", font.weight = "bold"))
            ,area(col = 2:6) ~ function(x) percent(x / 100, digits = 0)
            ,area(col = 2:6) ~ color_bar("#DeF7E9")))

我面临两个问题:

  1. 数字在表格输出中不显示为百分比。
  2. 最后一列似乎没有对齐,即

如果有人能帮助我了解我在这里缺少什么,我将不胜感激?

【问题讨论】:

  • 如果能显示示例的dput,测试起来会更容易
  • 感谢@akrun,我已经编辑了问题,使其更清晰
  • 知道了,我也加了。
  • 对我来说,数字是使用相同的脚本获得的百分比。您可以尝试从github 安装开发版并检查
  • 这适用于一列df %>% mutate(Agree = color_bar("#DeF7E9")(formattable::percent(Agree/100))) %>% formattable(),我很难让它与mutate_at() 一起使用。创意来自this post

标签: r kableextra formattable


【解决方案1】:

这是一个解决方案,但需要大量输入,我想可以使用mutate_at(),但我只是不知道如何在percent() 部分中传递列名。使用 . 会产生错误。

这适用于大量输入:

library(dplyr)
library(formattable)

df %>% 
  mutate(`Strongly agree` = color_bar("#DeF7E9")(formattable::percent(`Strongly agree`/100))) %>% 
  mutate(`Agree` = color_bar("#DeF7E9")(formattable::percent(`Agree`/100))) %>% 
  mutate(`Disagree` = color_bar("#DeF7E9")(formattable::percent(`Disagree`/100))) %>%
  mutate(`Neither agree nor disagree` = color_bar("#DeF7E9")(formattable::percent(`Neither agree nor disagree`/100))) %>%
  mutate(`Strongly disagree` = color_bar("#DeF7E9")(formattable::percent(`Strongly disagree`/100))) %>%
  formattable(.,
              align=c("l","l","l","l","l","l"),
              `ethnicity` = formatter("span", style = ~ style(color = "grey", font.weight = "bold")))

这不起作用,但可能会改进:

df %>% 
  mutate_at(.vars = 2:6, .funs = color_bar("#DeF7E9")(formattable::percent(./100))) %>% 
  formattable(...)

Some more informations about this "strange" structure var = color_bar(...)(var)

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多