title: How to build a function with summation
body: <p>I need to find a way to create a function that can work like the function <strong>counts</strong> described in the picture.</p>
  <p>This is what I tried so far working with a code from an answer I found <a href="https://stackoverflow.com/questions/52723061/creating-a-summation-formula-in-r">here</a>, but I can't work out how the elements that I see in that function can be translated to my case.</p>
  <p>Function I need to replicate<img src="https://i.stack.imgur.com/ORoYu.png" alt="" /></p>
  <p>How my database looks<img src="https://i.stack.imgur.com/ejXZ1.png" alt="" /></p>
  <p>Also, the function can actually be simplified with respect to the one above because the database already shows the total number of cites per year... Am I wrong? This is what I have so far:</p>
  <pre><code>j &lt;- patents_grant$Company
  t&lt;- patents_grant$Year
  x &lt;- patents_grant$count
  
  fun_counts &lt;- function(j,t) {
    for (i in j)
    sum(x[1:M, j], na.rm = T)
  }
  
  counts_try &lt;- sapply(1:j ,fun_counts, M=3)
  </code></pre>
  <p>I'm pretty sure this one must be easy to build and I just don't have the knowledge. So even if you just have suggestions on good places to look at to learn how to build functions, that would be immensely appreciated.</p>