테이블의 데이터 형식을 백분율로 지정
다음과 같은 데이터 프레임이 있습니다.
이 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(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")))
두 가지 문제가 있습니다.
- 숫자는 테이블 출력에 백분율로 표시되지 않습니다.
- 마지막 열에서 정렬이 꺼진 것 같습니다.
누군가가 내가 여기서 무엇을 놓치고 있는지 이해하도록 도와 줄 수 있다면 정말 고맙겠습니까?
답변
Paul
여기에 해결책이 있지만 많은 타이핑이 필요하지만 사용할 수 있다고 생각 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)