テーブル内のデータをパーセンテージでフォーマットする
Aug 18 2020
次のようなデータフレームがあります。

この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つの問題に直面しています:
- 数値は、テーブル出力にパーセンテージとして表示されません。
- 最後の列で配置がずれているようです。
誰かが私がここで何が欠けているのかを理解するのを手伝ってくれると本当にありがたいですか?

回答
Paul Aug 18 2020 at 15:12
これが解決策ですが、多くの入力が必要です。使用することは可能だと思います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(...)
この「奇妙な」構造に関するいくつかの詳細情報 var = color_bar(...)(var)