tags:

views:

786

answers:

3
+1  Q: 

Time series in R

Hi,

I am tracking my body weight in a spread sheet but I want to improve the experience by using R. I was trying to find some information about time series analysis in R but I was not succesful.

The data I have here is in the following format:

date -> weight -> body-fat-percentage -> water-percentage

e.g. 10/08/09 -> 84.30 -> 18.20 -> 55.3

What I want to do

plot weight and exponential moving average against time

How can I achieve that?

+3  A: 

Read the data into R using x <- read.csv(filename). Make sure the dates come in as character class and weight as numeric.
Then use the following:

require(zoo)
require(forecast) # Needed for the ses function
x$date <- as.Date(x$date,"%m/%d/%Y") # Guessing you are using the US date format
x$weight <- zoo(x$weight,x$date) # Allows for irregular dates
plot(x$weight, xlab="Date", ylab="Weight") # Produce time plot
ewma <- as.vector(fitted(ses(ts(x$weight)))) # Compute ewma with parameter selected using MLE
lines(zoo(ewma,x$date),col="red") # Add ewma line to plot
Rob Hyndman
There is the problem I have been facing in the past. All tutorials I found use a frequency. The data I have here are dates. I pretty much recorded my weight everyday. Once in a while I forgot it though. The result is, that there is no clear frequency but a date -> weight relationship.
Christian Stade-Schuldt
I've modified my answer to allow for irregular dates and no specified frequency.
Rob Hyndman
I tried your solution the chart works but when it comes to the smoothing I get the an error, that the object "wt" cannot be found.
Christian Stade-Schuldt
+1  A: 

Looks like you need to handle an irregularly spaced time series, so ts is not an option. Use one of the other time series libraries. zoo is the most widely used, but some other options are timeSeries, xts, fts, and its. Have a look at the CRAN view: http://cran.r-project.org/web/views/TimeSeries.html.

One challange that I can see right now is your date format. I suggest either reformatting the date first in your data or else using the format() function in R, but you will need to convert those into a Date or POSIX object in R to use it with a time series package.

You can use the read.zoo() function to read in your file a a time series. Also have a look at the vignette. For the EWMA, I believe that there are several options there too. Rmetrics and TTR both have versions.

I'll post an example when I get to a computer. Incidentally, there are many resources available on this subject. Have a look at this ebook: http://www.rmetrics.org/ebooks/TimeSeriesFAQ.pdf.

Shane
A: 

There is a really good book on Time Series in R just came out this summer

http://www.amazon.com/Introductory-Time-R-Use/dp/0387886974

if you'd like to dig deeper into the subject.

-k

knguyen