본문 바로가기

Programming/R Reference

R을 이용한 curve fitting

아주 간단하지만, 잘 정리되어 있는..


링크를 찾아서 기록을 남겨둡니다.


http://davetang.org/muse/2013/05/09/on-curve-fitting/




#fit first degree polynomial equation:
fit  <- lm(y~x)
#second degree
fit2 <- lm(y~poly(x,2,raw=TRUE))
#third degree
fit3 <- lm(y~poly(x,3,raw=TRUE))
#fourth degree
fit4 <- lm(y~poly(x,4,raw=TRUE))
#generate range of 50 numbers starting from 30 and ending at 160
xx <- seq(30,160, length=50)
plot(x,y,pch=19,ylim=c(0,150))
lines(xx, predict(fit, data.frame(x=xx)), col="red")
lines(xx, predict(fit2, data.frame(x=xx)), col="green")
lines(xx, predict(fit3, data.frame(x=xx)), col="blue")
lines(xx, predict(fit4, data.frame(x=xx)), col="purple")

#create function for the third order polynomial
third_order <- function(newdist, model) {
    coefs <- coef(model)
    #y = d + cx + bx^2 + ax^3
    res <- coefs[1] + (coefs[2] * newdist) + (coefs[3] * newdist^2) + (coefs[4] * newdist^3)
    return(res)
}
yy <- third_order(xx,fit3)
plot(xx,yy,type="l")
lines(x,y,col="red")


anova(fit2,fit3)



coef(fit)


'Programming > R Reference' 카테고리의 다른 글

IDE for R - NONMEM execution in R  (0) 2014.01.16
GUI or Workflow Engine / Bench for R  (0) 2014.01.16
Integrated Development Environment (IDE) for R  (0) 2014.01.16
R blog - TRinker's R Blog  (0) 2013.12.23
What to do with R  (0) 2013.12.17