[R] I think not so hard question

Liaw, Andy andy_liaw at merck.com
Thu Jan 12 20:41:29 CET 2006


Mark,

It's a bit unclear whether you're looking for a run of exactly 3, or at
least 3.  If it's exactly 3, what Prof. Koenker suggested (using rle())
should help you a lot.  If you want runs of at least 3, it should work
similarly as well.

> set.seed(1)
> (x <- sample(c(-1, 1), 100, replace=TRUE))
  [1] -1 -1  1  1 -1  1  1  1  1 -1 -1 -1  1 -1  1 -1  1  1 -1  1  1 -1  1
-1 -1 -1
 [27] -1 -1  1 -1 -1  1 -1 -1  1  1  1 -1  1 -1  1  1  1  1  1  1 -1 -1  1
1 -1  1
 [53] -1 -1 -1 -1 -1  1  1 -1  1 -1 -1 -1  1 -1 -1  1 -1  1 -1  1 -1 -1 -1
1  1 -1
 [79]  1  1 -1  1 -1 -1  1 -1  1 -1 -1 -1 -1 -1  1  1  1  1 -1 -1  1  1
> r <- rle(x)$length
> p <- which(r == 3)
> idx <- cumsum(r)[p] - 2
> sapply(idx, function(i) x[i:(i+2)])
     [,1] [,2] [,3] [,4]
[1,]   -1    1   -1   -1
[2,]   -1    1   -1   -1
[3,]   -1    1   -1   -1
> idx
[1] 10 35 62 73

Andy


From: Mark Leeds
> 
> I'm sorry to bother this list so much
> But I haven't programmed in
> A while and I'm struggling.
>  
> I have a vector in R of 1's and -1's
> And I want to use a streak of size Y
> To predict that the same value will
> Be next.
>  
> So, suppose Y = 3. Then,  if there is a streak of three 
> ones in a row, then I will predict that the next value is
> a 1. But, if there is a streak of 3 -1's in a row,
> then I will predict that a -1 is next. Otherwise,
> I don't predict anything.
>  
> I am really new to R and kind of struggling
> And I was wondering if someone could show
> how to do this ?
>  
> In other words, given a vector of -1's
> And 1's,  I am unable ( I've been trying
> For 2 days ) to create a new vector that
> Has the predictions in it at the appropriate
> places ? Thanks.
>  
>  
> 
> 
> **********************************************************************
> This email and any files transmitted with it are 
> confidentia...{{dropped}}
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list