title: How to append aggregated vectors for keyed data as a new column in R
body: <p>My R problem is the following: I have a data.frame from an SQL database (let's say security cash flows: 'cf_table'). The primary key is of 3 columns:</p>
  
  <pre><code>security_id, quote_date, future_cf_date, (and 'x')
  </code></pre>
  
  <p>On the 4th column (e.g. 'x') I shall make some computations what returns a vector (instead of single value), in my example <code>rev(cumsum(rev(x)))</code> -- backward cumulated sums, <strong>grouped by the first two cols</strong>. In other words: "What is the backward cumulated sums of future cashflows of a security by quote day?" 'x' is sparse, it has mainly NAs.  How can I accomplish this task? I tried <code>dplyr</code>, <code>data.table</code> etc. without success. My goal is to append this new column to my original table.</p>
  
  <p>For reproducibility please see the end of my post.</p>
  
  <p>Any idea? (By the way, is <code>rev(cumsum(rev(x)))</code> efficient or elegant?)</p>
  
  <p>Sample data:</p>
  
  <pre><code>cf_table &lt;- structure(list(security_id = structure(c(1L, 1L, 1L, 1L, 1L, 
  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
  1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a", 
  "b"), class = "factor"), quote_date = structure(c(2L, 2L, 2L, 
  2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 
  4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 3L, 3L, 3L, 4L, 4L, 4L), .Label = c("2014.05.13", 
  "2015.04.13", "2015.04.14", "2015.04.15"), class = "factor"), 
      CF.Dátum = structure(c(3L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
      3L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 3L, 5L, 6L, 7L, 8L, 9L, 
      10L, 11L, 1L, 2L, 4L, 1L, 2L, 4L, 1L, 2L, 4L), .Label = c("2014.12.22", 
      "2015.06.22", "2015.06.24", "2015.12.22", "2016.06.24", "2017.06.26", 
      "2018.06.25", "2019.06.24", "2020.06.24", "2021.06.24", "2022.06.24"
      ), class = "factor"), future_cf_date = c(NA, NA, NA, NA, 
      NA, 2000L, NA, 10000L, NA, NA, NA, NA, NA, 2000L, NA, 10000L, 
      NA, NA, NA, NA, NA, NA, NA, 10000L, NA, 500L, 10000L, NA, 
      NA, 10000L, NA, NA, 10000L), My.desired.output = c(12000L, 
      12000L, 12000L, 12000L, 12000L, 12000L, 10000L, 10000L, 12000L, 
      12000L, 12000L, 12000L, 12000L, 12000L, 10000L, 10000L, 10000L, 
      10000L, 10000L, 10000L, 10000L, 10000L, 10000L, 10000L, 10500L, 
      10500L, 10000L, 10000L, 10000L, 10000L, 10000L, 10000L, 10000L
      )), .Names = c("security_id", "quote_date", "future_cf_date", "x", 
  "My.desired.output"), class = "data.frame", row.names = c(NA, 
  -33L))
  </code></pre>