R 将表中的数据格式化为百分比
我有一个如下所示的数据帧: 以下是创建此DF的代码:R 将表中的数据格式化为百分比,r,kableextra,formattable,R,Kableextra,Formattable,我有一个如下所示的数据帧: 以下是创建此DF的代码: structure(list(ethnicity = structure(c(1L, 2L, 3L, 5L), .Label = c("AS", "BL", "HI", "Others", "WH", "Total"), class = "factor"), `Strongly agree` = c(3
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库来实现这一点(请参阅下面的代码)
我面临两个问题:
这里有一个解决方案,但它需要大量的键入,我想可以使用
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(...)
这里有一个解决方案,但它需要大量的键入,我想可以使用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(...)
如果你能显示示例的dput
,测试会更容易谢谢@akrun,我已经编辑了这个问题,以便它更清晰。我也添加了这个。对我来说,数字是使用相同的脚本以百分比的形式获得的。你能试着从github
安装devel版本并检查一列df%>%mutate(Agree=color\u bar(“#DeF7E9”)(formattable::percent(Agree/100))%%>%formattable()
,我很难让它与mutate\u at()一起工作。这个想法来自于如果你能展示这个例子的dput
,测试起来会更容易谢谢@akrun,我已经编辑了这个问题,这样它就更清晰了。我也添加了这个。对我来说,数字是用同一个脚本得到的百分比。你能试着从github
安装devel版本并检查一列df%>%mutate(Agree=color\u bar(“#DeF7E9”)(formattable::percent(Agree/100))%%>%formattable()
,我很难让它与mutate\u at()一起工作。这个想法来自