[R] Selecting the first occurrence of a value after an occurrence of a different value

Petr Savicky savicky at praha1.ff.cuni.cz
Mon Jan 17 09:50:19 CET 2011


On Sun, Jan 16, 2011 at 11:09:58PM -0800, surreyj wrote:
> 
> Hello, 
> 
> Back again, 
> 
> I thought the problem was solved but I realised that the only reason I was
> getting the correct answer was because my data set happened to only have two
> "rfts" to choose from, so it looked correct.
> 
> I have been using:
> 
> onlyfirstresponseafterrft<-which(!diff(as.numeric(factor(Stat, levels =
> c("MagDwn", "Resp")))))
[...]
> 
> to get my results and what is being delivered is the rows at which a "resp"
> occurs after a "magdwn" except I only want the first "resp" after a mag
> down... This seems simple to figure out and I have tried a lot of things but
> its just not happening!

Is it required to select positions with Resp, which are the
end-points of subsequences of the form MagDwn other^* Resp ?
For the sequence

  1  MagDwn
  2  other 
  3  MagDwn
  4  Resp  
  5  other 
  6  Resp  
  7  MagDwn
  8  other 
  9  Resp  

this would be positions 4 and 9.

The positions of Resp in these end-points may be computed,
for example

  Vals <- c("MagDwn", "Resp", "other")
  Stat <- Vals[c(1, 3, 1, 2, 3, 2, 1, 3, 2)]
  ind <- which(Stat %in% c("MagDwn", "Resp"))
  Reduced <- Stat[ind]
  ind[which(diff(Reduced == "Resp") == 1) + 1]
  # [1] 4 9

The positions of the corresponding MagDwn are

  ind[which(diff(Reduced == "Resp") == 1)]
  # [1] 3 7

Petr Savicky.



More information about the R-help mailing list