From: Jim Lemon <jim_at_bitwrit.com.au>

Date: Fri, 25 Jul 2008 21:11:42 +1000

R-help_at_r-project.org mailing list

https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 25 Jul 2008 - 11:11:34 GMT

Date: Fri, 25 Jul 2008 21:11:42 +1000

On Thu, 2008-07-24 at 06:57 -0700, nmarti wrote:

> I'm trying to calculate the percent change for a time-series variable.

*> Basically the first several observations often look like this,
**>
**> x <- c(100, 0, 0, 150, 130, 0, 0, 200, 0)
**>
**> and then later in the life of the variable they're are generally no more
**> 0's. So when I try to calculate the percent change from one observation to
**> the next, I end up with a lot of NA/Nan/INF, and sometimes 0's which is what
**> I want, in the beginning.
**>
**> I know I can use x <- na.omit(x), and other forms of this, to get rid of
**> some of these errors. But I would rather use some kind of function that
**> would by defult give a 0 while dividing by zero so that I don't lose the
**> observation, which is what happens when I use na.omit.
**>
**> I would imagine this is a common problem. I tried finding something in zoo,
**> but I haven't found what I'm looking for.
**>
*

Hi nmarti,

If you are looking for percent change, it is probably easiest to write a
little function that you can call for each pair of values. I'm assuming
that all of your values are >= 0.

pctchng<-function(x1,x2) {

# don't try to calculate the value

if(x1==0) {

# if the second value is zero, there is no change
if(x1==0) return(0)

# otherwise there is infinite change

# you may want to return another value here
else return(Inf)

}

# it's okay, calculate the percentage change
return(100*(x2-x1)/x1)

}

Jim

R-help_at_r-project.org mailing list

https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 25 Jul 2008 - 11:11:34 GMT

Archive maintained by Robert King, hosted by
the discipline of
statistics at the
University of Newcastle,
Australia.

Archive generated by hypermail 2.2.0, at Fri 25 Jul 2008 - 11:32:12 GMT.

*
Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help.
Please read the posting
guide before posting to the list.
*