如何在 R 中使用 tabyl 交叉制表 4 个变量

How to crosstab 4 variables using tabyl in R

我想按组 g 交叉表变量 xyz。我可以用 3 个变量 (tabyl(x,y,z)) 来完成,但我想对 g 的每个值重复它。我试过 group_by(g) 但没用。

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(janitor)
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test

df <- tibble(x = c(1, 2, 3, 3, 4, 3),
             y = c(1,1,1,2,2,2),
             z = c(1,2,1,1,2,2),
             g = c(1,1,1,1,2,2))

t <- df %>%
  tabyl(x,y,z)
t
#> $`1`
#>  x 1 2
#>  1 1 0
#>  2 0 0
#>  3 1 1
#>  4 0 0
#> 
#> $`2`
#>  x 1 2
#>  1 0 0
#>  2 1 0
#>  3 0 1
#>  4 0 1
Created on 2021-03-04 by the reprex package (v1.0.0)

我们可以使用 group_splitmap

library(dplyr)
library(janitor)
library(purrr)
df %>% 
     group_split(g) %>%
     map(~ .x %>% tabyl(x, y, z))