1

我有兴趣按样本类别总结几个结果并将其全部呈现在一张表中。输出类似于:

对比
圆柱体 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()and包显示了希望,CrossTable()但我看不出如何在不嵌套它们的情况下将其扩展到多组列。

如此处所示,ftable可以接近:

ftable(vs + am ~ cyl, mtcars)

除了嵌套amvs.

同样,dplyr通过例如接近

library(dplyr)
mtcars %>%
  group_by(cyl, vs, am) %>%
  summarize(count = n())

或者像这样更复杂的东西

但我有几个变量要呈现,这种嵌套破坏了我总结的能力。

也许aggregate可以在比我更聪明的人手中工作?

蒂亚!

4

2 回答 2

1
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
于 2022-01-24T23:19:22.167 回答
1

基于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
于 2022-01-25T01:13:20.207 回答