rpivot-tablecrosstab

How to make multi layer cross tabs in R


I am attempting to create a multi-layered cross tab in R. Currently, when using this code:

NewMexico_DEM_xtab_ <- NewMexico_DEM_Voterfile %>%
  group_by(Sex, CountyName) %>%
  tally() %>%
  spread(Sex, n)

I receive this output:

enter image description here

My goal is to add a layer for age using the Age column and for R to output a tab like this:

enter image description here

Is there a way I can do this with my current code or a package that would make this easier?


Solution

  • Do either of these approaches solve your problem?

    library(tidyverse)
    # Create sample data
    iris_df <- iris
    iris_df$Sample <- sample(c("M","F"), 150, replace = TRUE)
    
    # crosstabs
    iris_df %>%
      group_by(Species, Sample) %>%
      tally() %>%
      spread(Sample, n)
    #> # A tibble: 3 × 3
    #> # Groups:   Species [3]
    #>   Species        F     M
    #>   <fct>      <int> <int>
    #> 1 setosa        26    24
    #> 2 versicolor    25    25
    #> 3 virginica     27    23
    
    # Add in 'Age'
    iris_df$Age <- sample(c("18-24", "25-35", "36-45", "45+"), 150, replace = TRUE)
    
    # crosstabs
    iris_df %>%
      group_by(Species, Sample, Age) %>%
      tally() %>%
      spread(Age, n)
    #> # A tibble: 6 × 6
    #> # Groups:   Species, Sample [6]
    #>   Species    Sample `18-24` `25-35` `36-45` `45+`
    #>   <fct>      <chr>    <int>   <int>   <int> <int>
    #> 1 setosa     F            2       4      14     6
    #> 2 setosa     M           11       4       5     4
    #> 3 versicolor F            3       8       8     6
    #> 4 versicolor M            5       8       2    10
    #> 5 virginica  F            5       8       7     7
    #> 6 virginica  M            6      10       3     4
    
    # Using janitor::tabyl()
    library(janitor)
    #> 
    #> Attaching package: 'janitor'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     chisq.test, fisher.test
    iris_df %>%
      tabyl(Species, Sample, Age)
    #> $`18-24`
    #>     Species F  M
    #>      setosa 2 11
    #>  versicolor 3  5
    #>   virginica 5  6
    #> 
    #> $`25-35`
    #>     Species F  M
    #>      setosa 4  4
    #>  versicolor 8  8
    #>   virginica 8 10
    #> 
    #> $`36-45`
    #>     Species  F M
    #>      setosa 14 5
    #>  versicolor  8 2
    #>   virginica  7 3
    #> 
    #> $`45+`
    #>     Species F  M
    #>      setosa 6  4
    #>  versicolor 6 10
    #>   virginica 7  4
    

    Created on 2022-08-24 by the reprex package (v2.0.1)