Now would be an excellent time to read the help page for ?ave. You can specify multiple grouping variables. -- Sent from my phone. Please excuse my brevity.
On October 28, 2016 7:28:44 PM PDT, Ashta <sewa...@gmail.com> wrote: >Hi all thank you very much for your help. Worked very well for that >data set. I just found out that one of the data sets have another >level and do the same thing, I want to calculate the difference >between successive row values (num) to the first row value within >city and year. > >city, year, num >1, 2001, 25 >1, 2001, 75 >1, 2001, 150 >1, 2002, 35 >1, 2002, 65 >1, 2002, 120 >2, 2001, 25 >2, 2001, 95 >2, 2001, 150 >2, 2002, 35 >2, 2002, 110 >2, 2002, 120 > >The result will be > >city,year,num,Diff >1, 2001, 25, 0 >1, 2001, 75, 50 >1, 2001, 150, 125 >1, 2002, 35, 0 >1, 2002, 65, 30 >1, 2002, 120, 85 >2, 2001, 25, 0 >2, 2001, 95, 70 >2, 2001, 150, 125 >2, 2002, 35, 0 >2, 2002, 110, 75 >2, 2002, 120, 85 > >Thank you again > > >On Fri, Oct 28, 2016 at 4:08 AM, P Tennant <philipt...@iinet.net.au> >wrote: >> Hi, >> >> You could use an anonymous function to operate on each `year-block' >of your >> dataset, then assign the result as a new column: >> >> d <- data.frame(year=c(rep(2001, 3), rep(2002, 3)), >> num=c(25,75,150,30,85,95)) >> >> d$diff <- unlist(by(d$num, d$year, function(x) x - x[1])) >> d >> >> year num diff >> 1 2001 25 0 >> 2 2001 75 50 >> 3 2001 150 125 >> 4 2002 30 0 >> 5 2002 85 55 >> 6 2002 95 65 >> >> >> Philip >> >> >> On 28/10/2016 3:20 PM, Ashta wrote: >>> >>> Hi all, >>> >>> I want to calculate the difference between successive row values to >>> the first row value within year. >>> How do I get that? >>> >>> Here is the sample of data >>> Year Num >>> 2001 25 >>> 2001 75 >>> 2001 150 >>> 2002 30 >>> 2002 85 >>> 2002 95 >>> >>> Desired output >>> Year Num diff >>> 2001 25 0 >>> 2001 75 50 >>> 2001 150 125 >>> 2002 30 0 >>> 2002 85 55 >>> 2002 95 65 >>> >>> Thank you. >>> >>> ______________________________________________ >>> R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see >>> 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. >> >> ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see 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.