Paul-s
Paul-s

Reputation: 95

do until loop in R

at the end of my wits, so sorry this is the wrong place, or done incorrectly. first time asking here. i am new to R, with very little programming experience (a pascal class in college, and was very good at macromedia lingo way back - so, not that afraid of code).

to keep things short and simple, i think best to just show you what i have, and what i would like. i have spent hours upon hours searching and trying for a solution.

an example of what i have (it is an xts object called "signals", and indexed by days (left out here to make the example simple):

open  close position
0     0     0
1     0     0
0     0     0
0     0     0
0     1     0
0     0     0

and what i would like to happen:

open  close position
0     0     0
1     0     1
0     0     1
0     0     1
0     1     1
0     0     0

basically, when "open" is true, repeat 1s in "position" until "close" is true. amazingly simple, i think, but somehow i can't make it work. here one example of where i got that i thought was maybe close, but it gets stuck in an endless loop:

for (i in 1:nrow(signals)) {
  if (signals[i,"open"]==1) next
  while (signals[i,"close"] == 0) {
    signals[i,"position"] <- 1 }
}

thank you!

EDIT - i left out an important qualifier. there are times where the first true statement in "close" will come before the first true statement in "open." however, now that i wrote that out here, i suppose it is easier to just 'clean' the close column somehow, so there are no 1s in it prior to the point of the first 1 in the open column.

however, if someone has an idea how to do it all, feel free to add additional information. thanks!

Upvotes: 4

Views: 2552

Answers (1)

James
James

Reputation: 66874

You don't have to use loops for this:

open <- c(0,1,0,0,0,0)
close <- c(0,0,0,0,1,0)
position <- cumsum(open-close)
position
[1] 0 1 1 1 0 0

Note this closes immediately, if you want to on the line after you get a close signal, use:

cumsum(open-c(0,close[-length(close)]))
[1] 0 1 1 1 1 0

The reason your while statment never ends is that you have nothing to modify what is being tested, that is i doesn't get incremented.

Upvotes: 7

Related Questions