r - 按几列分组并打印
问题描述
我有一个数据框,我希望最后打印几列的结果,这些列按每列的观察次数及其频率分组。
这就是我所做的,但它给了我总数的计数和频率,但我想要每一列,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"))
解决方案
推荐阅读
- javascript - 如何使用对象数组访问 if?
- php - mysql查询:获取多表选择相关表的最后一行
- excel - 检查天数是否在日期范围内 Excel
- postgresql - go-gorm postgres dialect: managing structs for jsonb insert and find to properly use json tags
- excel - 如何在 Excel 中使用 VLOOKUP 修复 N/A 错误
- javascript - 即使使用插件也无法让 babel 转换传播运算符
- amazon-web-services - 使用 CloudFormation 模板创建的 S3 存储桶是否有“请求者付费”属性?
- amazon-web-services - 调整 AWS ECS Spot 请求
- javascript - 如何平滑地拉伸和收缩旋转线弧?
- django - 项目中使用的 Django Alter 命令行过滤器