【发布时间】:2011-05-21 21:25:59
【问题描述】:
我正在探索一些数据,所以我想做的第一件事是尝试对其进行正态(高斯)分布。这是我第一次在 R 中尝试这个,所以我一步一步来。首先,我预先合并了我的数据:
myhist = data.frame(size = 10:27, counts = c(1L, 3L, 5L, 6L, 9L, 14L, 13L, 23L, 31L, 40L, 42L, 22L, 14L, 7L, 4L, 2L, 2L, 1L) )
qplot(x=size, y=counts, data=myhist)
由于我想要计数,我需要添加一个归一化因子 (N) 来扩大密度:
fit = nls(counts ~ N * dnorm(size, m, s), data=myhist, start=c(m=20, s=5, N=sum(myhist$counts)) )
然后我创建了适合显示的数据,一切都很好:
x = seq(10,30,0.2)
fitted = data.frame(size = x, counts=predict(fit, data.frame(size=x)) )
ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() + geom_line(data=fitted)
当我发现这个讨论使用 geom_smooth() 一步完成所有操作的线程时,我很兴奋,但我无法让它工作:
这是我尝试的……以及我得到的:
ggplot(data=myhist, aes(x=size, y=counts)) + geom_point() + geom_smooth(method="nls", formula = counts ~ N * dnorm(size, m, s), se=F, start=list(m=20, s=5, N=300, size=10))
Error in method(formula, data = data, weights = weight, ...) :
parameters without starting value in 'data': counts
该错误似乎表明它正在尝试适应观察到的变量 counts,但这没有任何意义,如果我为也很重要:
fitting parameters ‘m’, ‘s’, ‘N’, ‘size’, ‘counts’ without any variables
Error in eval(expr, envir, enclos) : object 'counts' not found
知道我做错了什么吗?当然,这不是世界末日,但步骤越少越好,而且你们总是为这些常见任务想出最优雅的解决方案。
提前致谢!
杰弗里
【问题讨论】:
-
您提到您正在探索数据。是否必须适合
nls?使用简单的ggplot(myhist, aes(x = size, y = counts)) + geom_point() + geom_smooth()可以让你更轻松地适应黄土(我相信)。我确实希望有人能解释如何让nls工作,虽然......相当神秘。 -
我(不情愿地)来到自然科学的统计数据,所以“探索”往往意味着“时间适应高斯!”。不过说真的,我找到了一些很棒的资源,比如 Ricci 的“Fitting Distributions in R”(cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf)和 fitdistr() 上的这个 SO 答案(stackoverflow.com/questions/4290081/…),但没有一个旧的东西使用 ggplot2。
标签: r ggplot2 curve-fitting least-squares model-fitting