Andrew Bannerman
Andrew Bannerman

Reputation: 1305

Reference forward and behind vector element in calculation

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

enter image description here

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

Upvotes: 1

Views: 62

Answers (3)

Andrew Bannerman
Andrew Bannerman

Reputation: 1305

After a while figured it out with a for loop

i=1
start <- NULL
for( i in 1:length(vector)) {
  start[i] <- ifelse(vector[i + 1]==2,1,start[i - 1]+1)
}
start

Data:

 vector <- c(1,2,rep(1,24),2,1,1)

Upvotes: 0

Maurits Evers
Maurits Evers

Reputation: 50678

This reproduces your expected output.

x <- vector;
for (i in 1:length(x))
    if (x[i + 1] == 1 & !is.na(x[i + 1])) x[i] = 1 else x[i] = x[i - 1] + 1;
x;
# [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
#[26]  1  2  3  4

PS. vector is a very poor name for a variable in R.


Sample data

vector <- c(NA,1,rep(NA,24),1,NA,NA);

Upvotes: 2

Lamia
Lamia

Reputation: 3875

If I understand correctly what you're after, you could do this:

library(dplyr)
x = c(NA, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, NA, 1, 1, 0, 2, 5, 6, 1, 3)
y = (lead(x)!=1|is.na(lead(x)))
res = cumsum(y)-cummax((cumsum(y)-1)*!y)
[1] 1 2 3 4 5 6 1 2 3 4 5 6 1 1 2 3 4 5 1 2 3

This is a building up on one of the answers to this question.

Upvotes: 1

Related Questions