I have a data frame which records the skin temperature of a bunch of folks over time. I would like to:
- Fit a quadratic polynomial to each id's
SkinTemp
overTime
; - Calculate the curvature.
This seems much harder than it should be.
I asked about the first part in Fitting a quadratic curve for each data set that has different lengths, but I can't move forward to calculate derivatives and curvature.
df <- 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 %>% group_by(id) %>% do(model =
lm(SkinTemp ~ Time+I(Time^2), data = .))
Now I need to calculate the curvature k = y''/(1 + y' ^ 2) ^ (3 / 2)
, where y'
and y''
are 1st and 2nd derivative of y
with respect to x
.
I thought I could ask the predict
function to give me derivatives by passing for example deriv = 2
, but it doesn't seem to work.
predQ <- lapply(unique(df$id),
function(x) predict(deriv = 2,fitted_models$model[[x]]))
So I amended this function, which seems to work OK but isn't there a built-in function for this task?
deriv <- function(x, y) diff(y) / diff(x)
middle_pts <- function(x) x[-1] - diff(x) / 2
second_d <- 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])))