I have this vector:
vector <- c(NA,1,rep(NA,24),1,NA,NA)
[1] NA 1 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 1 NA NA
Essentially what I want to do is:
In excel the command is this: Calculation point = E40
=IF(B41=1,1,+E39+1)
In R it would be like:
ifelse([+1 forward] == 1,1,[-1 behind]+1)
It is basically a counter which resets to 1 when a 1 is encountered.
This is desired output:
> output
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 4
If we start in element 1, vector[1]
then we are looking at vector[2]
with the statement ifelse([+1 forward],1,1
in this case, this is true so we place 1... next we move up a element position. Now we in position 2.. vector[2]. The statement is now looking for a ifelse([+1 forward],1,1 in vector[3], if its not a 1, else its taking vector[1]
and adding a +1. Next thing... at position vector[3]
, the statement is now looking for a ifelse([+1 forward],1,1 in vector[4]
, if its not a 1, else its taking vector[2] and adding a +1.. so a running counter... eventually we meet another 1, then the counter will reset to 1... and we begin counting again... until next 1.
making sense maybe?
here is how it works in excel
This is what I have tried:
vector <- c(NA,1,rep(NA,24),1,NA,NA)
i=1
for( i in 1:length(vector)) {
start <- ifelse(vector[i + 1]==1,1,vector[i - 1]+1)
}
start