Fitting a function in R

匆匆过客 提交于 2019-12-03 07:41:53

Maybe using a cubic specification for your model and estimating via lm would give you a good fit.

# Importing your data
dataset <- read.table(text='
    x   y
1   0 123
2   2 116
3   4 113
4  15 100
5  48  87
6  75  84
7 122  77', header=T)

# I think one possible specification would be a cubic linear model
y.hat <- predict(lm(y~x+I(x^2)+I(x^3), data=dataset)) # estimating the model and obtaining the fitted values from the model

qplot(x, y, data=dataset, geom="line") # your plot black lines
last_plot() + geom_line(aes(x=x, y=y.hat), col=2) # the fitted values red lines

# It fits good.

Try taking the log of your response variable and then using lm to fit a linear model:

fit <- lm(log(y) ~ x, data=mydata)

The adjusted R-squared is 0.8486, which at face value isn't bad. You can look at the fit using plot, for example:

plot(fit, which=2)

But perhaps, it's not such a good fit after all:

last_plot() + geom_line(aes(x=x, y=exp(fit$fitted.values)))

Check this document out: http://cran.r-project.org/doc/contrib/Ricci-distributions-en.pdf

In brief, first you need to decide on the model to fit onto your data (e.g., exponential) and then estimate its parameters.

Here are some widely used distributions: http://www.itl.nist.gov/div898/handbook/eda/section3/eda366.htm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!