Fitting a function in R

后端 未结 3 1169
抹茶落季
抹茶落季 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: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

提交回复
热议问题