1
start <- as.POSIXct("2016-09-19")
end <- start + as.difftime(14, units="days")
datetime <- seq(from=start, to=end, by="days")
signal <- c(0,0,1,1,0,0,0,0,1,0,1,1,0,0,0)
price <- c(seq(22.0, 23.4, by=.2), seq(23.4, 22.2, by=-.2))
df <- data.frame(datetime, signal,price)
df$Up_or_down <- 0

I added a datetime column which might be helpful in sequencing.

I have a dataframe of prices and a signal. I need to:

  1. Find the first instance of the signal (signal == 1)
  2. Take the price from the row of the first signal and determine
  3. Did the price go up or down at least $1?
  4. Place a -1 or +1 in the Up_or_down column at the row of the first signal.

Here's the tricky part: I then need to start at the NEXT signal(in this case it is the next row), and find if the price move $1 up or down from that 2nd starting row.

So, start at the first signal, find if the price moved up or down, then start again at the next signal.

dataframe

user5249203
  • 4,436
  • 1
  • 19
  • 45
RandyMy
  • 1,013
  • 1
  • 8
  • 9

2 Answers2

0

why dont you sort by signal, and then calculate range per signal

I am sorry , can you paste the data instead of the picture so I can work on it

Extract rows for the first occurrence of a variable in a data frame

also

dataset1=NULL
dataset1$signal=c(0,0,1,1,0,0,0,0,1,0,1,1,0,0,0)
dataset1$price=c(22.0,22.2,22.4,22.6,22.8,23.0,23.2,23.4,23.4,23.2,23.0,22.8,22.6,22.4,22.2)
dataset1=data.frame(dataset1)
dataset1
dataset1[order(dataset1$signal),]

library(Hmisc)
summarize(dataset1$price,dataset1$signal,range)
Community
  • 1
  • 1
Ajay Ohri
  • 3,382
  • 3
  • 30
  • 60
0

I figured this out using an index that skips the signals that are irrelevant. Thanks.

RandyMy
  • 1,013
  • 1
  • 8
  • 9