[R] How do I subtract sequential values ?

Peter Ehlers ehlers at ucalgary.ca
Mon Nov 29 04:58:08 CET 2010


On 2010-11-28 19:38, Joshua Wiley wrote:
> Hi Eric,
>
> I think this does what you want.  It may be a simple question, but
> that does not necessarily mean the easiest/fastest answer is
> intuitive.  Welcome to R!
>
> dat<- data.frame(v = 1:100)
> ## the with() is just a convenient way to avoid having to type
> ## dat$v every single time---similar to attach(), but cleaner
> ## the idea is to create three vectors, that are offset by removing
> ## either the first observation or the last
> with(dat, (v[-1] - v[-length(v)])/v[-length(v)])
>
> HTH,
>
> Josh
>

That's a good first-time user solution.
Then, since this is R, here's the next step:

  v <- sample(50, 100, replace = TRUE)
  result <- diff(v) / v[-length(v)]

Peter Ehlers

> On Sun, Nov 28, 2010 at 7:29 PM, eric<ericstrom at aol.com>  wrote:
>>
>> Just starting to learn R so excuse me if this is a simple question. I'm
>> wondering how I get the percent difference in sequential values in one
>> column of a dataframe. If I had a dataframe and one of the columns was
>> "value", how would I go about calculating  (v2-v1)/v1 ....(v3-v2)/v2
>> ....(v4-v3)/v3 ...etc ?
>> --
>> View this message in context: http://r.789695.n4.nabble.com/How-do-I-subtract-sequential-values-tp3063019p3063019.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> 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.
>>
>
>
>



More information about the R-help mailing list