title: How to apply 'lapply' for this function? (R)
body: <p>I have a function that calculates 'incremental AUC(area under the curve)' when given certain values per time points (0, 15, 30, ... 120min). I want to apply this function to batch calculate my columns and ideally create a new 'list' that contains only the 'auc' values from each run, but having trouble coding this. I was thinking 'lapply' may work, but wonder if there are better suggestions since I would be creating similar functions and run them in batch in futures. Thank you so much guys.
  Below is the function where the data frame=df1, CAT.12 being one of the columns. X is the time while y being the variable (column).</p>
  <pre><code>i_auc.fn &lt;- function(x,y) {
    auc &lt;- ifelse(y[2] &gt; y[1], (y[2]-y[1])*(x[2]-x[1])/2, 0)
    seg.type &lt;- 0
    for (i in 3:length(x)) {
      if (y[i] &gt;= y[1] &amp; y[i-1] &gt;= y[1]) {
        auc[i-1] &lt;- (((y[i]-y[1])/2) + (y[i-1]-y[1])/2) * (x[i]-x[i-1])/2
        seg.type[i-1] &lt;- 1
      } else if (y[i] &gt;= y[1] &amp; y[i-1] &lt; y[1]) {
        auc[i-1] &lt;- ((y[i]-y[1])^2/(y[i]-y[i-1])) * (x[i]-x[i-1])/2
        seg.type[i-1] &lt;- 2
      } else if (y[i] &lt; y[1] &amp; y[i-1] &gt;= y[1]) {
        auc[i-1] &lt;- ((y[i-1]-y[1])^2/(y[i-1]-y[i])) * (x[i]-x[i-1])/2
        seg.type[i-1] &lt;- 3
      } else if (y[i] &lt; y[1] &amp; y[i-1] &lt; y[1]) {
        auc[i-1] &lt;- 0
        seg.type[i-1] &lt;- 4
      } else {
        # The above cases are exhaustive, so this should never happpen
        return(cat(&quot;i:&quot;, i, &quot;Error: No condition met\n&quot;))
      }
    }
    return(list(auc=sum(auc), segments=auc, seg.type=seg.type))
  }
  iAUC &lt;- i_auc.fn(df1$time, df1$CAT.12)
  </code></pre>
  <p><a href="https://i.stack.imgur.com/fmmDQ.png" rel="nofollow noreferrer">my df1 looks like this</a></p>