title: In R, can I make the table() function return the number of NA values in a named element?
body: <p>I am using R to summarize a large amount of data for a report. I want to be able to use <code>lapply()</code> to generate a list of tables from the <code>table()</code> function, from which I can extract my desired statistics. There are a lot of these, so I've written a function to do it. My issue is that I am having difficulty returning the number of missing (<code>NA</code>) values even though I have that in each table, because I can't figure out how to tell R that I want the element from <code>table()</code> that holds the number of <code>NA</code> values. As far as I can tell, R is "naming" that element <code>NA</code>...and I can't call that.</p>
  
  <p>I'm trying to avoid writing some complex statement where I say something like <code>which(is.na(names(element[1]))) | names(element[1])=="var_I_want"</code> because I feel like that's just really wordy. I was hoping there was some way to either tell R to label the <code>NA</code> variable in each table with a character name, or to tell it to pick the one labeled <code>NA</code>, but I haven't had much luck yet.</p>
  
  <p>Minimal example:</p>
  
  <pre><code>example &lt;- data.frame(ID=c(10,20,30,40,50),
                        V1=c("A","B","A",NA,"C"),
                        V2=c("Dog","Cat",NA,"Cat","Bunny"),
                        V3=c("Yes","No","No","Yes","No"),
                        V4=c("No",NA,"No","No","Yes"),
                        V5=c("No","Yes","Yes",NA,"No"))
  
  varlist &lt;- c("V1","V2","V3","V4","V5")
  
  list_o_tables &lt;- lapply(X=example[varlist],FUN=table,useNA="always")
  
  list(V1=list_o_tables[["V1"]]["A"],
       V2=list_o_tables[["V2"]]["Cat"],
       V3=list_o_tables[["V3"]]["Yes"],
       V4=list_o_tables[["V4"]]["Yes"],
       V5=list_o_tables[["V5"]]["Yes"])
  </code></pre>
  
  <p>What I get:</p>
  
  <pre><code>$V1
  A 
  2 
  
  $V2
  Cat 
    2 
  
  $V3
  Yes 
    2 
  
  $V4
  Yes 
    1 
  
  $V5
  Yes 
    2
  </code></pre>
  
  <p>What I'd like:</p>
  
  <pre><code>$V1
  A     &lt;NA&gt;
  2       1
  
  $V2
  Cat   &lt;NA&gt;
    2     1
  
  $V3
  Yes   &lt;NA&gt; 
    2     0
  
  $V4
  Yes   &lt;NA&gt; 
    1     1
  
  $V5
  Yes   &lt;NA&gt; 
    2     1
  </code></pre>