[R] Conditional operation on data frame, shift/roll of vector
David Winsemius
dwinsemius at comcast.net
Sat Sep 26 18:52:09 CEST 2009
On Sep 26, 2009, at 11:46 AM, jiangrm wrote:
> Conditionally, when Ind of a certain row is 1, want to get sum or
> delta of Val in that row and 1 row
> above.
>
> Val Ind Val Ind Del
> 10 0 10 0 NA
> 11 0 11 0 NA
> 13 1 -------> 13 1 24 or 2
> 16 0 16 0 NA
>
> A simple way I guess is to get shifted vector of Val (say, c(NA, 10,
> 11, 13)), add to or minus from
> Val, then and logically AND with Ind.
?diff
> df1<-data.frame(Val=c(10,11,13,16), Ind=c(0,0,1,0))
> c(NA, diff(df1$Val))[df1$Ind==1]
[1] 2
>
> Which function provides the shift operation of the vector Val?
?"[" # with a suitable index vector
?lag # for time series
>
> Also welcomed if any better way to do this. Thanks.
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list