[英]Creating Crosstable with Multiple Variables Summarized by Row Categories
我有興趣按樣本類別總結幾個結果並將其全部呈現在一張表中。 與 output 類似的東西:
對比 | 是 | |||
---|---|---|---|---|
圓柱體 | 0 | 1 | 0 | 1 |
4 | 1 | 10 | 3 | 8 |
6 | 3 | 4 | 4 | 3 |
8 | 14 | 0 | 12 | 2 |
我是否能夠組合(“ cbind
”)以下生成的表:
ftable(mtcars$cyl, mtcars$vs)
並通過:
ftable(mtcars$cyl, mtcars$am)
crosstable()
和CrossTable()
包顯示了 promise 但我看不出如何將其擴展到多組列而不嵌套它們。
如此處所示, ftable
可以接近:
ftable(vs + am ~ cyl, mtcars)
除了在vs
中嵌套am
之外。
同樣, dplyr
通過例如,
library(dplyr)
mtcars %>%
group_by(cyl, vs, am) %>%
summarize(count = n())
或者像這樣更復雜的東西
但我有幾個變量要呈現,這種嵌套破壞了我總結的能力。
也許aggregate
可以在比我更聰明的人手中工作?
蒂亞!
foo = function(df, grp, vars) {
lapply(vars, function(nm) {
tmp = as.data.frame(as.matrix(ftable(reformulate(grp, nm), df)))
names(tmp) = paste0(nm, "_", names(tmp))
tmp
})
}
do.call(cbind, foo(mtcars, "cyl", c("vs", "am", "gear")))
# vs_0 vs_1 am_0 am_1 gear_3 gear_4 gear_5
# 4 1 10 3 8 1 8 2
# 6 3 4 4 3 2 4 1
# 8 14 0 12 2 12 0 2
基於purrr::map_dfc
和tidyr::pivot_wider
的解決方案:
library(tidyverse)
map_dfc(c("vs", "am", "gear"), ~ mtcars %>% pivot_wider(id_cols = cyl,
names_from = .x, values_from = .x, values_fn = length,
names_prefix = str_c(.x, "_"), names_sort = T, values_fill = 0) %>%
{if (.x != "vs") select(.,-cyl) else .}) %>% arrange(cyl)
#> This message is displayed once per session.
#> # A tibble: 3 × 8
#> cyl vs_0 vs_1 am_0 am_1 gear_3 gear_4 gear_5
#> <dbl> <int> <int> <int> <int> <int> <int> <int>
#> 1 4 1 10 3 8 1 8 2
#> 2 6 3 4 4 3 2 4 1
#> 3 8 14 0 12 2 12 0 2
這並不是真正的計划,但您可以使用 package 交叉表,在一個簡單的left_join()
調用的幫助下做到這一點:
library(tidyverse)
library(crosstable)
ct1 = crosstable(mtcars, cyl, by=vs)
ct2 = crosstable(mtcars, cyl, by=am)
ct = left_join(ct1, ct2, by=c(".id", "label", "variable"),
suffix=c("_vs", "_am"))
ct
#> # A tibble: 3 × 7
#> .id label variable `0_vs` `1_vs` `0_am` `1_am`
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 cyl cyl 4 1 (9.09%) 10 (90.91%) 3 (27.27%) 8 (72.73%)
#> 2 cyl cyl 6 3 (42.86%) 4 (57.14%) 4 (57.14%) 3 (42.86%)
#> 3 cyl cyl 8 14 (100.00%) 0 (0%) 12 (85.71%) 2 (14.29%)
as_flextable(ct)
由代表 package (v2.0.1) 於 2022 年 6 月 16 日創建
也許有一天我會為交叉表添加一個cbind()
方法,以便as_flextable()
output 看起來更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.