将表格中的数据格式化为百分比

时间:2020-08-17 21:55:37

标签: r kableextra formattable

我有一个看起来像这样的数据框:My data frame

以下是创建此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")))

我面临2个问题:

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

如果有人能帮助我了解我在这里想念的是什么,我将不胜感激?

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个解决方案,但需要大量输入,我想可以使用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)