Saturday, August 21, 2010

R - Fitting data using Linear Models

Linear Model explanation
http://stat.ethz.ch/R-manual/R-devel/library/stats/html/lm.html

Formula object explanation
http://stat.ethz.ch/R-manual/R-devel/library/stats/html/formula.html

Example

x <- seq(0, 10, 0.1)

y <- 1 + x + cos(x) + rnorm(x)
yy <- 1 + x + cos(x)

plot(x, y, lwd = 3)
lines(x, yy, lwd = 3)

# 1 (default) includes intercept - 0 no
fit <- lm(y ~ 1 + x + I(x^2) + I(cos(x)))
fit
summary(fit)

newdf <- data.frame(x <- seq(11,2000,0.1))
newdf <- data.frame(newdf,y <- 1 + newdf$x + cos(newdf$x) + rnorm(newdf$x))
newp <- predict(fit,newdf)

plot(newdf$x,newdf$y,lwd=3)
lines(newdf$x,newp,lwd=3)

No comments:

Post a Comment