The power of R: curve fitting

August 15, 2006

I’ve got a bunch of XY cartesian coords that I want to plot. When charted the curves are jagged. Fortunately, each point has an associated weight – the number of observations used to create it. So how do I fit a curve to the data, using the weights to smooth and reduce the influence of the outlying points resulting from fewer observations ?

With R, it’s easy…

# x,y define straight line at 45%
x <- 0:19
y <- 0:19

# make the line jagged by shifting points
# [down,no move, up] in a repeating group of 3
y <- y + (-1:1)
plot(x,y,type=’b’)
# generate vector of weights that give more
# weight to the unshifted points
w <- rep(0,20)
w <- w + c(1,3,1)

# reconstruct the unshifted straight line
f <- glm.fit(x,y,w)
lines(x,f$fitted.values)

Advertisements

2 Responses to “The power of R: curve fitting”


  1. […] I’m using R to fit curves to data that has outliers backed by low observation counts. I’ve been thrashing round trying different R fitting methods, including glm.fit. But linear fits were obviously wrong. Not being a maths graduate, I was a bit stumped until I had a chat with one of our more maths and tech minded model traders. He looked at my charts and data, and suggested a weighted least squares fit. […]

  2. Mark Says:

    This line will fail if pasted into anyones R session because one of the single quotes is a back quote

    plot(x,y,type=’b’)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s