Fitting a function in R

后端 未结 3 1168
抹茶落季
抹茶落季 2021-02-04 09:25

I have a few datapoints (x and y) that seem to have a logarithmic relationship.

> mydata
    x   y
1   0 123
2   2 116
3   4 113
4  15 100
5  48  87
6  75  84         


        
相关标签:
3条回答
  • 2021-02-04 09:51

    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)))
    
    0 讨论(0)
  • 2021-02-04 09:51

    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

    0 讨论(0)
  • 2021-02-04 09:55

    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.
    

    enter image description here

    0 讨论(0)
提交回复
热议问题