首页 > 解决方案 > 按几列分组并打印

问题描述

我有一个数据框,我希望最后打印几列的结果,这些列按每列的观察次数及其频率分组。

这就是我所做的,但它给了我总数的计数和频率,但我想要每一列,q1a,q1a_30d,q1a_60d,q1a_90d

a<- df %>% group_by(q1a, q1a_30d, q1a_60d,q1a_90d) %>% summarise(cnt = n()) %>%mutate(freq = formattable::percent(cnt / sum(cnt),1))

然后打印

kable( a, col.names = c(" ", "cnt", "freq"),align = c("lcr"),longtable = T, booktabs = T, valign = 't', escape = F,  caption = '<b> Wore a face covering or mask<b>')  %>%
  kable_styling(bootstrap_options = c("striped", "hold_position"),full_width = T,position = "center",html_font = "Arial") %>%
  add_header_above(c("Baseline", "30 days", "60 days", "90 days"))%>%
  column_spec(border_left = T, border_right = T)
dput(a[1:10, ])

structure(list(q1a = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,1L, 1L, 1L), .Label = c("All of the time", "Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), q1a_30d = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,2L), .Label = c("All of the time", "Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), q1a_60d = structure(c(1L, 1L, 1L, 1L, 2L, 3L, 5L, 1L, 2L, 2L), .Label = c("All of the time", "Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), q1a_90d = structure(c(1L, 2L, 3L, 5L,5L, 1L, 5L, 1L, 1L, 3L), .Label = c("All of the time", "Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), cnt = c(8L, 1L, 1L, 13L, 1L, 1L, 14L, 4L, 1L, 1L), freq = structure(c(0.347826086956522, 0.0434782608695652, 0.0434782608695652, 0.565217391304348, 1, 1, 1, 1, 0.5, 0.5), formattable = list(formatter = "formatC", format = list(format = "f", digits = 1), preproc = "percent_preproc", postproc = "percent_postproc"), class = c("formattable", "numeric"))), row.names = c(NA, -10L), groups = structure(list(q1a = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("All of the time", "Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), q1a_30d = structure(c(1L, 1L, 1L, 1L,2L, 2L), .Label = c("All of the time", "Very frequently","Somewhat frequently", "Never", "No answer"), class = "factor"),q1a_60d = structure(c(1L, 2L, 3L, 5L, 1L, 2L), .Label = c("All of the time","Very frequently", "Somewhat frequently", "Never", "No answer"), class = "factor"), .rows = structure(list(1:4, 5L, 6L,7L, 8L, 9:10), ptype = integer(0), class = ("vctrs_list_of","vctrs_vctr", "list"))), row.names = c(NA, -6L), class = c("tbl_df","tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", "data.frame"))

标签: rgroup-by

解决方案


推荐阅读