title: Nested lapply() in a list?
body: <p>I have a list <code>l</code>, which has the following features:</p>
  
  <ul>
  <li>It has 3 elements</li>
  <li>Each element is a numeric vector of length 5</li>
  <li>Each vector contains numbers from 1 to 5</li>
  </ul>
  
  <hr>
  
  <pre><code>l = list(a = c(2, 3, 1, 5, 1), b = c(4, 3, 3, 5, 2), c = c(5, 1, 3, 2, 4))
  </code></pre>
  
  <p>I want to do two things:</p>
  
  <p><strong>First</strong></p>
  
  <p>I want to know how many times each number occurs in the entire list and I want each result in a vector (or any form that can allow me to perform computations with the results later):</p>
  
  <p>Code 1:</p>
  
  <pre><code>&gt; a &lt;- table(sapply(l, "["))
  &gt; x &lt;- as.data.frame(a)
  &gt; x
  
    Var1   Freq
  1    1   3
  2    2   3
  3    3   4
  4    4   2
  5    5   3
  </code></pre>
  
  <p>Is there anyway to do it without using the <code>table()</code> function. I would like to do it "manually". I try to do it right below.</p>
  
  <p>Code 2: (I know this is not very efficient!)</p>
  
  <pre><code>x &lt;- data.frame(
  "1" &lt;- sum(sapply(l, "[")) == 1
  "2" &lt;- sum(sapply(l, "[")) == 2
  "3" &lt;- sum(sapply(l, "[")) == 3
  "4" &lt;- sum(sapply(l, "[")) == 4
  "5" &lt;- sum(sapply(l, "[")) == 5)
  </code></pre>
  
  <p>I tried the following, but I did not work. I actually did not understand the result.</p>
  
  <pre><code>&gt; sapply(l, "[") == 1:5        
  
       a     b     c
  [1,] FALSE FALSE FALSE
  [2,] FALSE FALSE FALSE
  [3,] FALSE  TRUE  TRUE
  [4,] FALSE FALSE FALSE
  [5,] FALSE FALSE FALSE
  
  &gt; sum(sapply(l, "[") == 1:5)
  
  [1] 2
  </code></pre>
  
  <p><strong>Second</strong></p>
  
  <p>Now, I would like to get the number of times each number appears in the list, but now in each element <code>$a</code>, <code>$b</code> and <code>$c</code>. I thought about using the <code>lapply()</code> but I don't know how exactly. Following is what I tried, but it is inefficient just like <em>Code 2</em>:</p>
  
  <pre><code>lapply(l, function(x) sum(x == 1))
  lapply(l, function(x) sum(x == 2))
  lapply(l, function(x) sum(x == 3))
  lapply(l, function(x) sum(x == 4))
  lapply(l, function(x) sum(x == 5))
  </code></pre>
  
  <p>What I get with these 5 lines of code are 5 lists of 3 elements each containing a single numeric value. For example, the second line of code tells me how many times number <code>2</code> appears in each element of <code>l</code>.</p>
  
  <p>Code 3:</p>
  
  <pre><code>&gt; lapply(l, function(x) sum(x == 2))
  
  $a
  [1] 1
  
  $b
  [1] 1
  
  $c
  [1] 1
  </code></pre>
  
  <p>What I would like to obtain is a list with three elements containing all the information I am looking for.</p>
  
  <p>Please, use the references "Code 1", "Code 2" and "Code 3" in your answers. Thank you very much.</p>