title: Subject-specific age at peak velocity from linear mixed natural spline model with spline random effects
body: <p>I am using a linear mixed effects model with a natural spline function for age to describe the trajectory of an outcome <code>y</code> (measured in grams) across time (<code>age</code> in years) in a sample of individuals. My model includes random-effects for splines (with fewer degrees of freedom than the fixed-effects splines).</p>
  <p>I would like to estimate the subject-specific (person-specific) age at peak velocity from this model.</p>
  <p>A <a href="https://stackoverflow.com/questions/65509039/individual-age-at-peak-velocity-from-linear-mixed-natural-spline-model">previous thread</a> describes how to estimate the subject-specific age at peak velocity when the model contains a quadratic random-effects age term.</p>
  <p>The code below provides the example dataset and shows how the model was fit, how the mean trajectory was plotted and how the mean velocity curve and mean age at peak velocity were calculated.</p>
  <p>How can I estimate the age at peak velocity for each individual from this model?</p>
  <pre><code># LOAD DATASET
  library(RCurl)
  dat &lt;- read.csv((&quot;https://raw.githubusercontent.com/aelhak/data/main/data.csv&quot;))
  
  # FIT MODEL
  library(nlme)
  library(splines)
  model &lt;- lme( # linear mixed-effects model
    y ~ ns(age, df = 7), # FE: natural spline function for age with 6 knots
    random = ~ ns(age, df = 3) | id, # RE: natural spline function for age with 2 knot
    method = &quot;ML&quot;, data = dat)
  
  # PLOT MEAN FITTED TRAJECTORY CURVE
  pred &lt;- data.frame(age = seq(min(dat$age), max(dat$age), length = 100))
  pred$pred &lt;- predict(model, pred, level = 0)
  
  library(tidyverse)
  ggplot(data = pred, aes(x = age, y = pred)) + geom_line()
  </code></pre>
  <p><a href="https://i.stack.imgur.com/GGrvl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GGrvl.png" alt="Plot of mean trajectory" /></a></p>
  <pre><code># PLOT MEAN VELOCITY CURVE
  library(SplinesUtils)
  spl_population &lt;- RegSplineAsPiecePoly(model, &quot;ns(age, df = 7)&quot;)
  plot(spl_population, deriv = 1)
  </code></pre>
  <p><a href="https://i.stack.imgur.com/RDine.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RDine.png" alt="Plot of mean velocity curve" /></a></p>
  <pre><code># ESTIMATE MEAN AGE AT PEAK VELOCITY AND PEAK VELOCITY
  (apv_mean &lt;- solve(spl_population, b = 0, deriv = 2)) 
  (pv_mean &lt;- predict(spl_population, apv_mean, deriv = 1))
  (apv_pv_mean &lt;- as.data.frame(cbind(apv_mean, pv_mean)))
  (apv_pv_mean &lt;- apv_pv_mean %&gt;% top_n(1, pv_mean))
  
  # apv_mean = 14.09897 years
  # pv_mean = 317.1267 grams
  </code></pre>