title: Calculate derivatives & curvature of a polynomial
body: <p>I have a data frame which records the skin temperature of a bunch of folks over time. I would like to:</p>
  
  <ol>
  <li>Fit a quadratic polynomial to each id's <code>SkinTemp</code> over <code>Time</code>;</li>
  <li>Calculate the curvature.</li>
  </ol>
  
  <p>This seems much harder than it should be.</p>
  
  <p>I asked about the first part in <a href="https://stackoverflow.com/questions/48687685/fitting-a-quadratic-curve-for-each-data-set-that-has-different-lengths/48687746#48687746">Fitting a quadratic curve for each data set that has different lengths</a>, but I can't move forward to calculate derivatives and curvature.</p>
  
  <pre><code>df &lt;- data.frame(Time = seq(65),
                   SkinTemp = rnorm(65, 37, 0.5),
                   id = rep(1:10, c(5,4,10,6,7,8,9,8,4,4)))
  
  #Predict data points for each quadratic
  fitted_models = df %&gt;% group_by(id) %&gt;% do(model =
                  lm(SkinTemp ~ Time+I(Time^2), data = .))
  </code></pre>
  
  <p>Now I need to calculate the curvature <code>k = y''/(1 + y' ^ 2) ^ (3 / 2)</code>, where <code>y'</code> and <code>y''</code> are 1st and 2nd derivative of <code>y</code> with respect to <code>x</code>.</p>
  
  <p>I thought I could ask the <code>predict</code> function to give me derivatives by passing for example <code>deriv = 2</code>, but it doesn't seem to work.</p>
  
  <pre><code>predQ &lt;- lapply(unique(df$id),
                  function(x) predict(deriv = 2,fitted_models$model[[x]])) 
  </code></pre>
  
  <p>So I amended this function, which seems to work OK but isn't there a built-in function for this task?</p>
  
  <pre><code>deriv &lt;- function(x, y) diff(y) / diff(x)
  middle_pts &lt;- function(x) x[-1] - diff(x) / 2
  second_d &lt;- lapply(unique(df$id),
                     function(x) deriv(middle_pts(df$Time[df["id"]==x]), deriv(df$Time[df["id"]==x], df$SkinTemp[df["id"]==x])))
  </code></pre>