r - 使用 R 拟合“多峰”对数正态分布
问题描述
我的问题与此处的问题类似,但我想在 R 中进行。数据框是
x<-c(0.35,0.46,0.60,0.78,1.02,1.34,1.76,2.35,3.17,4.28,5.77,7.79,10.50,14.20,19.10,25.80)
y<-c(32.40,43.00,37.20,26.10,17.40,14.00,19.90,36.90,48.60,55.30,64.60,70.20,63.90,47.60,22.70,10.30)
df<-data.frame(x,y)
plot(df,log='xy')
在这里绘制的是数据的外观。以 x 刻度为单位,有一种模式约为 0.5,另一种模式约为 8。
如何将“多峰”对数正态分布拟合到此类数据(在本例中为 2 条曲线)?这是我尝试过的。非常感谢任何帮助或解决它的方向。
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
stat_smooth(method="nls",
formula=y ~ a*dlnorm(x, meanlog=8, sdlog=2.7),
method.args = list(start=c(a=2e6)),
se=FALSE,color = "red", linetype = 2)+
scale_x_log10()+
scale_y_log10()
解决方案
我假设你想要nls
. 您可以通过在方程式中定义两个参数来考虑两种模式,例如a
和b
。定义两个start=
ing 值。(注意,此时我只是猜到了所有的值。)
fit <- nls(y ~ a*dlnorm(x, meanlog=.5, sdlog=.5) + b*dlnorm(x, meanlog=8, sdlog=2.7),
data=df1, start=list(a=1, b=1))
summary(fit)
# Formula: y ~ a * dlnorm(x, meanlog = 0.5, sdlog = 0.5) + b * dlnorm(x,
# meanlog = 8, sdlog = 2.7)
#
# Parameters:
# Estimate Std. Error t value Pr(>|t|)
# a -81.97 16.61 -4.934 0.00022 ***
# b 30695.42 2417.90 12.695 4.53e-09 ***
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 11.92 on 14 degrees of freedom
#
# Number of iterations to convergence: 1
# Achieved convergence tolerance: 4.507e-07
fitted()
y
已经为您提供了x
数据框值的拟合值。
fitted(fit)
# [1] 45.56775 44.59130 38.46212 27.34071 15.94205 12.76579 21.31640
# [8] 36.51385 48.68786 53.60069 53.56958 51.40254 48.41267 44.95541
# [15] 41.29045 37.41424
# attr(,"label")
# [1] "Fitted values"
你也可以用predict()
这个。
stopifnot(all.equal(predict(fit), as.numeric(fitted(fit))))
但是,要获得更平滑的线,您需要一个predict
离子(即y
值)x
沿着您的x
轴的一组更精细的值。
plot(df1, log='xy')
x.seq <- seq(0, max(df$x), .1)
lines(x=x.seq, y=predict(fit, newdata=data.frame(x=x.seq)), col=2)
旁注:即使这很常见,通过命名数据框df
,您使用的名称与用于df()
F 分布的密度函数的名称相同,这可能会导致混淆!出于这个原因,我使用了df1
.
数据:
df1 <- structure(list(x = c(0.35, 0.46, 0.6, 0.78, 1.02, 1.34, 1.76,
2.35, 3.17, 4.28, 5.77, 7.79, 10.5, 14.2, 19.1, 25.8), y = c(32.4,
43, 37.2, 26.1, 17.4, 14, 19.9, 36.9, 48.6, 55.3, 64.6, 70.2,
63.9, 47.6, 22.7, 10.3)), class = "data.frame", row.names = c(NA,
-16L))
推荐阅读
- kubernetes - Kubernetes 自动缩放和创建/删除 Pod 的日志
- javascript - 数组元素的问题和Javascript中的随机化
- excel - 如何在 CubeMember 函数中向当前存在的函数添加第二个条件以返回 ID 字段
- postgresql - 跨区域复制 EC2 机器
- apache-superset - 如何根据经常更改的最新日期过滤仪表板?
- r - 如何将矩阵转换为R中的数据框?
- javascript - Express 未正确评估 id 字符串
- azure - 如何查看资源是否由 Azure 服务主体创建?
- c# - asp.net webform:RegisterClientScriptBlock 不适用于 jquery
- php - 在 Angular 应用程序(Laravel API)和 Laravel Web 应用程序之间保留的跨域 cookie