Reputation: 1148
I've begun working with spline in R. I would like to create a spline that is forced to go through the data points in my data. Here's some example code:
x <- 1:12
y <- c(2172205, 5332408, 10453117, 16038564, 21109922,
27966857, 33563819, 39948003, 42629618, 45226902,
46172149, 46805245)
z <- spline(x, y, 36)
> plot(z)
> print(z)
$x
[1] 1.000000 1.314286 1.628571 1.942857 2.257143 2.571429 2.885714 3.200000 3.514286 3.828571 4.142857
[12] 4.457143 4.771429 5.085714 5.400000 5.714286 6.028571 6.342857 6.657143 6.971429 7.285714 7.600000
[23] 7.914286 8.228571 8.542857 8.857143 9.171429 9.485714 9.800000 10.114286 10.428571 10.742857 11.057143
[34] 11.371429 11.685714 12.000000
$y
[1] 2172205 2869024 3855824 5086171 6514487 8101175 9809181 11599445 13406684 15147279 16741530 18233441
[13] 19806294 21649308 23806067 26054346 28143697 29930437 31596698 33386543 35470344 37630794 39523543 40845316
[25] 41679456 42321140 43055048 43928388 44777465 45433385 45831051 46053800 46196328 46338922 46528029 46805245
What I would like is to have the values of the individual points in the spline as shown here, but forcing the line through each individual x and y component originally given. So, 5332408 should show up in the y output and 2 should show up in the x.
I realize this could give me a worse, less smooth curve, but that's okay for my purposes. Any help is greatly appreciated and thank you in advance!
Upvotes: 1
Views: 535
Reputation: 263301
Use splinefun
instead of spline
to see that you actually do get the points intersecting the curve:
zf <- splinefun(x, y)
print( list(seq(36), y2=zf(seq(36) ) ) )
#----------
[[1]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
[25] 25 26 27 28 29 30 31 32 33 34 35 36
$y2
[1] 2172205 5332408 10453117 16038564 21109922 27966857
[7] 33563819 39948003 42629618 45226902 46172149 46805245
[13] 48751454 53350661 61942754 75867617 96465137 125075200
[19] 163037692 211692499 272379506 346438600 435209667 540032593
[25] 662247264 803193565 964211384 1146640605 1351821115 1581092800
[31] 1835795545 2117269238 2426853763 2765889007 3135714856 3537671196
y %in% zf(seq(36) )
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Upvotes: 2