This is actually a continuation of a previous question:
Spline on multiple factors in data frame
so apologies for going through the first part again. And believe me I tried to solve myself!
So some sample data:
mydf<- data.frame(c("a","a","b","b","c","c"),c("e","e","e","e","e","e")
,as.numeric(c(1,2,3,10,20,30)),
as.numeric(c(5,10,20,20,15,10)))
Give some names:
colnames(mydf)<-c("Model", "Class","Seconds", "Speed")
which gives:
> mydf
Model Class Seconds Speed
1 a e 1 5
2 a e 2 10
3 b e 3 20
4 b e 10 20
5 c e 20 15
6 c e 30 10
Now originally I needed to spline this data and the answer was kindly given as:
library("plyr")
ddply(mydf, .(Model), summarise, Spline = spline(x = Seconds, y = Speed))
which resulted in:
Model Spline
1 a 1.0, 1.2, 1.4, 1.6, 1.8, 2.0
2 a 5, 6, 7, 8, 9, 10
3 b 3.0, 4.4, 5.8, 7.2, 8.6, 10.0
4 b 20, 20, 20, 20, 20, 20
5 c 20, 22, 24, 26, 28, 30
6 c 15, 14, 13, 12, 11, 10
Just as a side note I couldn’t even by hand create this exact structure in R so as to provide an example, even by hand!
So back to the question. I need to change the results so they look something like this:
Model Seconds Speed
a 1.0 5
a 1.2 6
a 1.4 7
a 1.6 8
a 1.8 9
a 2.0 10
b 3.0 20
b 4.4 20
b 5.8 20
b 7.2 20
b 8.6 20
b 10.0 20
c 20 15
c 22 14
c 24 13
c 26 12
c 28 11
c 30 10
Thanks for any help!
You mean like this:
Now, you might be asking yourself, “How did joran figure that out?” Cuz before I read this question, I hadn’t the foggiest notion what
splinereturned.So my first stop was
?spline, and I skip to the Value section, where I find:Ah ha! So for each chunk of the data that
ddplyships off to our as yet unwritten function, it needs to take that list of two components and simply convert them into a data frame, so thatddplycan easily stitch things back together again.Hence I write a function that starts out by simply fitting the
splinemodel:and then takes the results and packages it into a data frame: