Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time series in R

Tags:

r

time-series

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 successful.

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?

like image 212
Christian Stade-Schuldt Avatar asked Feb 28 '23 05:02

Christian Stade-Schuldt


2 Answers

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
like image 65
Rob Hyndman Avatar answered Mar 07 '23 15:03

Rob Hyndman


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.

like image 37
Shane Avatar answered Mar 07 '23 14:03

Shane