การจัดรูปแบบข้อมูลในตารางเป็นเปอร์เซ็นต์

Aug 18 2020

ฉันมี dataframe ที่มีลักษณะดังนี้:

นี่คือรหัสสำหรับสร้าง 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")))

ฉันประสบปัญหา 2 ประการ:

  1. ตัวเลขจะไม่ปรากฏเป็นเปอร์เซ็นต์ในผลลัพธ์ของตาราง
  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)