"All Arguments Must Have the Same Length" Error When Using a Function to Create Multiple Crosstabs and Frequency Tables
<p>My question has two parts: </p>

<p>First, I'm attempting to use "apply" and a function in order to create multiple frequency tables and crosstabs for a data frame. I figured out how to make it work for the small data frame included below, but when I try to apply it to my real data (the str is included below as well) I get an error that "all arguments must have the same length".  </p>

<p>Second, I'm curious to know if there are any other ways of creating multiple frequency tables and crosstabs using purrr functions, or more efficient code. I'm still relatively new to R, so I imagine there is always a better way. As a bonus, it would be great to also include chi-square tests as well as bar charts along with each table using ggplot2. I haven't been able to figure out how to add this onto anonymous functions (listed below). Perhaps I'm being too ambitious, but it would be great to learn how to achieve all of this in one go with minimal code. </p>

<p>So below is the basic example data frame. I used apply and an anonymous function along with table() to produce frequency tables of each column except age, and then to create crosstabs of "Affected" against "Pet","City", and "Sex". </p>

<pre><code>Affected&lt;-c("Employee","Client","Employee","Volunteer","Volunteer","Client")
Pet&lt;-c("Cat","Cat","Dog","Iguana","Rabbit","Iguana")
Age&lt;-c(20,34,55,53,22,44)
City&lt;-c("Toronto","Vancouver","Montreal","Toronto","Alberta","Montreal")
Sex&lt;-c("Male","Male","Female","Male","Female","Male")

DF&lt;-data.frame(Affected,Pet,Age,City,Sex)

DF%&gt;%select(1:2,4:5)%&gt;%apply(.,2,table)

apply(DF,2,function(x)table(Affected,x))

DF%&gt;%select(1:2,4:5)%&gt;%apply(.,2,function(x)table(Affected,x))
</code></pre>

<p>However, when I try to apply this code to a larger data frame (the structure is below), I get an error:</p>

<blockquote>
  <p>Error in table(Affected, x) : all arguments must have the same length</p>
</blockquote>

<pre><code>data.frame':    52 obs. of  3 variables:

 $ Affected                     : Factor w/ 5 levels "Dog","Cat","Fish",..: 3 3 3 3 5 3 3 1 3 3 ...

 $ Department.Program           : Factor w/ 10 levels "A","B","C","D",..: 10 10 10 10 1 4 NA 10 1 9 ...

 $ Where.did.the.incident.occur.: Factor w/ 5 levels "Toronto","Vancouver",..: 3 1 3 3 3 3 3 2 3 3 ...
</code></pre>

<p>The data frame is referred to as Inc and below is the code I attempted that produced the error message. </p>

<pre><code>apply(Inc,2,function(x)table(Affected,x))
</code></pre>

<p>I'm hoping that by including the str of the data frame that it's enough to figure out the problem. </p>