Re: [R] Differences per group

From: Jorge Ivan Velez <jorgeivanvelez_at_gmail.com>
Date: Wed, 09 Mar 2011 16:55:32 -0500

Hi Rens,

One way would be

x$difference <- do.call(c, with(x, tapply(amount, customer, function(x) c(0, diff(x)))))
x

Take a look at ?tapply and ?aggregate for more information.

HTH,
Jorge

On Wed, Mar 9, 2011 at 10:27 AM, rens_1112 <> wrote:

> Dear all,
>
> Probably a rather stupid question, but I couldn't find the answer..
>
> I currently have a dataframe with customers' id's and purchase amount, what
> I would like to do is to show the difference between amount purchased
> compared to the month before per customer.
>
> I have made some attempts myself using diff, but what i can not get to work
> is that each different customer starts with a 0.
>
> This is an example of what I have:
>
> >purchase_amount
> customer amount
> 123 6
> 123 5
> 123 9
> 123 8
> 123 11
> 123 7
> 230 19
> 230 18
> 230 12
> 230 17
> 380 7
> 380 9
> 380 2
> 380 7
> 380 8
> 380 8
> 380 6
> 380 8
>
> How I would like it to look like:
>
> customer amount difference
> 123 6 0
> 123 5 -1
> 123 9 4
> 123 8 -1
> 123 11 3
> 123 7 -4
> 230 19 0
> 230 18 -1
> 230 12 -6
> 230 17 5
> 380 7 0
> 380 9 2
> 380 2 -7
> 380 7 5
> 380 8 1
> 380 8 0
> 380 6 -2
> 380 8 2
>
> I hope my question is clear like this.
> Many thanks in advance
> Rens
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/Differences-per-group-tp3343800p3343800.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.
>

        [[alternative HTML version deleted]]



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 Wed 09 Mar 2011 - 22:09:44 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 Wed 09 Mar 2011 - 22:10:20 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.

list of date sections of archive