R中小数据集的样条函数
我一直在用R中可用的各种不同的样条函数来描述一个非常小的数据集。我想,如果数据集大得多,任意数量的曲线都会像我预期的那样,但这种情况下的数据是有限的。下面的代码显示了我正在处理的数据类型的示例:R中小数据集的样条函数,r,spline,R,Spline,我一直在用R中可用的各种不同的样条函数来描述一个非常小的数据集。我想,如果数据集大得多,任意数量的曲线都会像我预期的那样,但这种情况下的数据是有限的。下面的代码显示了我正在处理的数据类型的示例: library(ggplot2); library(stats) dat <- data.frame(x = c(0.333, 0.5, 1, 2, 3, 4, 5), y = c(5.875e-03, 1.225e-02, 3.902e-02, 8.942e
library(ggplot2); library(stats)
dat <- data.frame(x = c(0.333, 0.5, 1, 2, 3, 4, 5),
y = c(5.875e-03, 1.225e-02, 3.902e-02, 8.942e-03,
4.277e-03, 1.938e-03, 1.131e-03))
mod <- splinefun(dat$x, dat$y, method = "monoH.FC")
mod <- data.frame(x = seq(0.333, 5, by = 0.1), y = mod(seq(0.333, 5, by = 0.1)))
ggplot() + geom_point(data = dat, aes(x = x, y = y)) +
geom_line(data = mod, aes(x = x, y = y))
库(ggplot2);图书馆(统计)
dat听起来你想要的是使拟合更接近中间的线性,我认为你可以通过将中点插值为真实点来实现:
dat2 = data.frame(x = union(dat$x,dat$x - c(0,diff(dat$x)/2)),
y = interp1(dat$x,dat$y,xi = union(dat$x,dat$x - c(0,diff(dat$x)/2))))
(interp1
在这里可能是不必要的,联合(dat$y,dat$y-c(0,diff(dat$y)/2))
也应该这样做,但上面的代码可以工作。)
编辑:注意,为了使diff
正常工作,您需要先对数据进行正确排序
这将创建一个新的data.frame,其中的点位于以前的点之间,如果现在对其进行样条拟合,则会对更线性的拟合进行加权
EDIT2:也可以通过这种方式使用带权重的平滑样条线,并将中间点的权重设置为低于主点的权重:
mod <- splinefun(dat$x, dat$y,method = 'monoH.FC')
mod2 <- data.frame(x = seq(0.333, 5, by = 0.1), y = mod(seq(0.333, 5, by = 0.1)))
# A set of weights, where each point in-between is weighted half as much
dat2$w <- rep(c(0.5,1),ceiling(length(dat2$x)/2))[-1]
# Smoothing Spline
modelspline <- smooth.spline(dat2$x, dat2$y,dat2$w)
# Plot points
xplot <- seq(min(dat2$x),max(dat2$x),by = 0.1)
# And Plot comparison
ggplot() +
geom_point(data = dat, aes(x = x, y = y)) +
geom_line(data = mod2, aes(x = x, y = y)) +
geom_line(data = data.frame(predict(modelspline,xplot)),
aes(x = x, y = y),color = 'red')
mod您是否检查了rms
软件包?它充满了用于拟合曲线的易于使用的函数。