Formatando dados em uma tabela como porcentagem
Eu tenho um dataframe parecido com este:

Aqui está o código para criar este 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")
Quero adicionar barras de dados e transformar esses números em porcentagens. Tentei usar a biblioteca formatável para fazer isso (veja meu código abaixo).
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")))
Estou enfrentando 2 problemas:
- Os números não aparecem como uma porcentagem na saída da tabela.
- O alinhamento parece incorreto na última coluna, ou seja,
Agradeceria muito se alguém pudesse me ajudar a entender o que estou perdendo aqui?

Respostas
Aqui está uma solução, mas requer muita digitação, acho que é possível usar, mutate_at()
mas simplesmente não consigo descobrir como passar nomes de coluna na percent()
parte. Usar o .
produz um erro.
Isso funciona com muita digitação:
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")))
Isso não funciona, mas pode ser melhorado:
df %>%
mutate_at(.vars = 2:6, .funs = color_bar("#DeF7E9")(formattable::percent(./100))) %>%
formattable(...)
Mais algumas informações sobre esta estrutura "estranha" var = color_bar(...)(var)