Searching Two Columns in a Data Frame in R

Viewed 1172

I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321

If we start at the bottom of the data frame and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again) and that the Midquotes value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

3 Answers
Related