[R] difference

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Fri Oct 28 22:14:31 CEST 2016


Haven't seen a solution using ave...

d$diff <- ave( d$num, d$year, FUN = function( v ) { v - v[ 1 ] } )
-- 
Sent from my phone. Please excuse my brevity.

On October 28, 2016 12:46:15 PM CDT, William Dunlap via R-help <r-help at r-project.org> wrote:
>You could use match() to find, for each row, the index of the first
>row with the give row's year:
>
>> d <- data.frame(year=c(rep(2001, 3), rep(2002, 3)),
>                  num=c(25,75,150,30,85,95))
>> indexOfFirstOfYear <- with(d, match(year, year))
>> indexOfFirstOfYear
>[1] 1 1 1 4 4 4
>> d$diff <- d$num - d$num[indexOfFirstOfYear]
>> 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
>
>
>Bill Dunlap
>TIBCO Software
>wdunlap tibco.com
>
>On Thu, Oct 27, 2016 at 9:20 PM, Ashta <sewashm at gmail.com> 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 at 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.
>>
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at 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.



More information about the R-help mailing list