使用Lattice(panel.smoother)或ggplot提取用于获得最佳拟合的方程式

3
我有100多个文件,其中的数据趋势几乎相同。我已经成功地为它们获得了最佳拟合度,但现在我想将其与理论论证进行比较。换句话说,我想生成一个方程,用于基于实验数据生成的最佳拟合曲线;该方程将适用于特定范围内的任何随机值,并产生类似的曲线,当然会有一些误差。
代码:
set.seed(42)
x <-sort(round(runif(10,0,53)))   ## random x values
y <- runif(10,0,400)              ## random y values
data1 <-  data.frame(y=y,x=x)     ## creating a data frame

现在我可以像下面这样使用lattice

library(lattice)
library(latticeExtra)
xyplot(y ~ x,data=data1,par.settings = ggplot2like(),
                   panel = function(x,y,...){
                     panel.xyplot(x,y,...)
                   })+ layer(panel.smoother(y ~ x, se = FALSE, span = 0.5))

或者使用以下的ggplot
library(ggplot2)
ggplot(data1, aes(x=x, y=y)) + geom_point() + geom_smooth(se = FALSE)

我想知道它的方程,或者说这个曲线的一些参数(系数、标准误差值等)。

enter image description here

1个回答

4

光滑器通常比你所理解的更加复杂。它们通常只在局部定义,因此没有全局方程,就像多项式拟合一样。默认情况下,panel.smoother函数使用loess平滑器,并且从您对xyplot的调用返回的对象中没有方程。相反,在面板节点的lay节点中保留了对panel.smoother函数的调用:

 myplot <- xyplot(y ~ x,data=data1,par.settings = ggplot2like(),
               panel = function(x,y,...){
                 panel.xyplot(x,y,...)
               })+ layer(panel.smoother(y ~ x, se = FALSE, span = 0.5))
 get('lay', envir = environment(myplot$panel))
#-------------
[[1]]
expression(panel.smoother(y ~ x, se = FALSE, span = 0.5))
attr(,"under")
[1] FALSE
attr(,"superpose")
[1] FALSE

attr(,"class")
[1] "layer"   "trellis"

这显示了在评估该表达式时会产生什么结果:
mysmooth <- loess(y~x)
str(mysmooth)
#--------
List of 17
 $ n        : int 10
 $ fitted   : num [1:10] 176 312 275 261 261 ...
 $ residuals: Named num [1:10] 6.78 -24.43 98.8 -159.25 -75.9 ...
  ..- attr(*, "names")= chr [1:10] "1" "2" "3" "4" ...
 ----------- omitting remaider of output------------

我使用xyplot-smoother,因为在 ggplot 函数结果中查找代码细节的任务比应用于 lattice 对象更加复杂。这个故事的寓意是:如果您想要一个具有特定复杂性和可定义特征的函数,则使用适当的样条函数,例如生存分析中的splinepsspline,或者 rms 中的rcs


非常感谢。在你的帖子之前,我实际上并不理解平滑器的功能。 str() 的结果正是我所需要的。使用这些值,我认为我可以创建我需要的方程。splines() 似乎也很好用。再次感谢。 - Ayushi Kachhara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接