如何解决将表格中的数据格式化为百分比
以下是创建此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"),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个问题:
如果有人能帮助我了解我在这里想念的是什么,我将不胜感激?
解决方法
这是一个解决方案,但需要大量输入,我想可以使用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"),`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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。