[R] How do I subtract sequential values ?

Joshua Wiley jwiley.psych at gmail.com
Mon Nov 29 04:38:06 CET 2010


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

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



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list