[R] how to code it??
Matt Shotwell
shotwelm at musc.edu
Wed Jul 28 22:06:43 CEST 2010
If I take your meaning correctly, you want something like this.
> x <- c(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0,
+ 1)
> easy <- function(x) {
+ state <- 0
+ for (i in 1:length(x)) {
+ if (x[i] == 0)
+ x[i] <- state
+ state <- 0
+ if (x[i] == 1)
+ state <- -1
+ }
+ x
+ }
> easy(x)
[1] 0 0 0 0 0 0 0 1 -1 0 1 1 -1 0 1 -1 0 0 1
-Matt
On Wed, 2010-07-28 at 14:10 -0400, Raghu 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.
>
> Many thx
--
Matthew S. Shotwell
Graduate Student
Division of Biostatistics and Epidemiology
Medical University of South Carolina
More information about the R-help
mailing list