微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将表格中的数据格式化为百分比

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

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

解决方法

这是一个解决方案,但需要大量输入,我想可以使用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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?