How to crosstab 4 variables using tabyl in R

Viewed 62

I want to crosstab variables x , y, z by group g. I can do it with 3 variables (tabyl(x,y,z)) but I want to repeat it for each value of g. I tried group_by(g) but it didn't work.

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)
1 Answers

We could use group_split with map

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