I have a data.frame with x,y coordinates and a grouping variable :
df<-data.frame(group=c(rep(1,3),rep(2,3),rep(3,3)),
x=c(rep(c(1,2,3),3)),
y=c(1,2,3,1,4,9,1,8,27))
I would like to have a splinefunction fitted to each group for later use. Something in the lines of:
df %>% group_by(group) %>% .... foo(splinefun(x,y))
I do not care for the original data (which contains more than group,x,y), so the return values could be a named list of functions, or anything i can reference with the group variable and get the fitted spline function. Use case is iterating over a second dataset with group and interpolation coordinate x. Anyone?
Edit
So an updated example with newData wich contains a group not included in the tibble of fitted functions:
df<-data.frame(group=c(rep(1,4),rep(2,4),rep(3,4)),
x=c(rep(c(0,1,2,3),3)),
y=c(0,1,2,3,0,1,4,9,0,1,8,27))
fit<-df %>%
group_by(group) %>%
summarise(fns = list(approxfun(x, y)))
newData <- data.frame(group=c(rep(1,5),rep(2,5),rep(3,5),rep(4,5)) ,
xval = rep(c(0,1,2,3,4),4)) %>%
left_join(fit)
So the fitted power functions are now joined with the expanded set of groups, where column fns is NULL on the missing records. If i can now mutate newData with column interpolated applying the functions where fns is not NULL and NA otherwise, I would be done.