On Sep 26, 2009, at 12:52 PM, David Winsemius wrote:
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
I suppose I ought to answer the question more fully. One approach
using indexing, is to use the logical vector produced by df1$Ind==1
on both sides of an assignment operation at once to determine which of
the values of hte above set of differences get transfered:
> df1$Del[df1$Ind==1] <- c(NA, diff(df1$Val))[df1$Ind==1]
> df1
Val Ind Del
1 10 0 NA
2 11 0 NA
3 13 1 2
4 16 0 NA
ifelse might also provide a solution. Something along the lines of:
df1$Del3 <- ifelse(df1$Ind ==1, c(NA, df1$Val[2:nrow(df1)]-df1$Val[1:
(nrow(df1)-1)]), NA)
But that seems so Baroque that I think you will agree that the
indexing method is preferable in this question.
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
______________________________________________
R-help@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.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
______________________________________________
R-help@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.