[R] Simple - Finding vector in a vector

Jessica Streicher j.streicher at micromata.de
Mon Oct 8 16:19:01 CEST 2012


> x<-c(NA , 1 ,NA,  1 , 1 , 1 , 1 , 1  ,1 ,NA , 1)
> embed(x,3)
      [,1] [,2] [,3]
 [1,]   NA    1   NA
 [2,]    1   NA    1
 [3,]    1    1   NA
 [4,]    1    1    1
 [5,]    1    1    1
 [6,]    1    1    1
 [7,]    1    1    1
 [8,]   NA    1    1
 [9,]    1   NA    1

> which(rowSums(embed(x,3))==3)
[1] 4 5 6 7

gives you the first of the 3

On 08.10.2012, at 15:38, Mike Spam wrote:

> Sorry, i just realized, that it output the sum of all vectors. I can
> work with this function but it would be much faster and easier if it
> would be possible to get the positions of evry match.
> 
> example:
> 
> NA  1 NA  1  1  1  1  1  1 NA  1
> 
> rle returns
> lengths: int [1:6] 1 1 1 6 1 1
> 
> what i need would be something like,
> 1 1 1 3 3 3 3 1 1
> 
> but anyway i can work with rle, if there is no suitable function.
> 
> thanks,
> Nico
> 
> 
> 
> 2012/10/8 Mike Spam <ichmagspam at googlemail.com>:
>> Hey Rui,
>> 
>> Perfect! Thanks!! :)
>> 
>> Nico
>> 
>> 2012/10/8 Rui Barradas <ruipbarradas at sapo.pt>:
>>> Hello,
>>> 
>>> See ?rle
>>> 
>>> Hope this helps,
>>> 
>>> Rui Barradas
>>> Em 08-10-2012 13:55, Mike Spam escreveu:
>>>> 
>>>> Hi,
>>>> 
>>>> just a simple question.
>>>> Assumed i have a vector,
>>>> 
>>>> FALSE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE
>>>> or
>>>> NA  1  1  1 NA  1 NA  1 NA
>>>> 
>>>> what i need is the position where an element is the same - three (or
>>>> in general multiple) times in a row.
>>>> 
>>>> in this case: i want to get the position where it is TRUE TRUE TRUE or 1 1
>>>> 1
>>>> it doesn't matter if it is the first, middle or last element. So the
>>>> output could be 2 or 3 or 4
>>>> 
>>>> My idea would be to lag the vector and calc differences... but i would
>>>> prefer any build in (or time saving) function. :)
>>>> 
>>>> thanks,
>>>> 
>>>> Nico
>>>> 
>>>> ______________________________________________
>>>> R-help at r-project.org mailing list
>>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>>> PLEASE do read the posting guide
>>>> http://www.R-project.org/posting-guide.html
>>>> and provide commented, minimal, self-contained, reproducible code.
>>> 
>>> 
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list