On Wed, Jul 28, 2010 at 2:10 PM, Raghu <r.raghura...@gmail.com> wrote: > Hi > > I have say a large vector of 3500 digits. Initially the digits are 0s and > 1s. I need to check for a rule to change some of the 0s to -1s in this > vector. But once I change a 0 to -1 then I need to start applying the rule > to change the next 0 only after I see the next 1 in the vector. > > Say for example x = (0,0,0,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,1) > I need to traverse from the 9th element to the last ( because the first > occurrence of 1 is at 8) . Let us assume that according to our rule we > change the 13th element (only 0s can be changed) to -1. Now we need to go to > the next occurrence of 1 (which is 15) and begin the rule application from > the 16th till the end of the vector and once replaced a 0 to a -1 then start > again from the next 1. How do we code this? I 'feel' recursion is the best > possible solution but I am not a programmer and will await experts' views. > If this is not a typical R-forum question then my advance apologies. >
If you are asking to replace the first 0 after any string of 1s with a -1 then try this: > replace(x, c(FALSE, diff(x) < 0), -1) [1] 0 0 0 0 0 0 0 1 -1 0 1 1 -1 0 1 -1 0 0 1 ______________________________________________ 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.