[R] How to search for a sequence(and its combination) inside a vector?
C W
tmrsg11 at gmail.com
Sat Jul 20 18:36:55 CEST 2013
Hi Berend
I am looking for a table,
# of times one element (out of 1, 2, 3) showed up, two elements, and all three.
I am trying, don't know if this works:
> aa <- rle(a)
> b <- aa$lengths[aa$values]
> table(b)
b
1 3
3 12
Mike
On Sat, Jul 20, 2013 at 12:24 PM, Berend Hasselman <bhh at xs4all.nl> wrote:
>
> On 20-07-2013, at 18:05, C W <tmrsg11 at gmail.com> wrote:
>
>> Hi R list,
>>
>> I have a sequence repeating 1:15 . Some numbers are deleted. I want
>> to find how many times 1, 2, 3 appeared.
>> Basically, I want to "grab" the beginning of the sequence and tally it up.
>>
>> R code:
>>
>>> vec <- c(1, 2, 3, 4, 5, 6, 7, 8, 13, 1, 2, 3, 5, 7, 8, 10, 12, 13, 14,
>> 15, 1, 2, 3, 5, 6, 10, 12, 13, 1, 2, 3, 4, 5, 6, 7, 12, 13, 14,
>> 15, 1, 2, 3, 6, 9, 10, 11, 13, 14, 1, 7, 10, 13, 1, 2, 3, 4,
>> 6, 7, 9, 11, 14, 1, 2, 3, 5, 9, 10, 11, 12, 14, 1, 2, 3, 4, 1,
>> 2, 3, 4, 11, 12, 14, 1, 2, 3, 4, 8, 11, 12, 1, 2, 3, 4, 5, 7,
>> 8, 9, 11, 12, 15, 3, 14, 1, 2, 3, 6, 10, 11, 13, 14, 1)
>>
>>> a <- vec %in% c(1, 2, 3)
>>> a
>> [1] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
>> TRUE TRUE FALSE FALSE
>> [15] FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE
>> FALSE FALSE FALSE FALSE
>> [29] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
>> FALSE TRUE TRUE TRUE
>> [43] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
>> TRUE TRUE TRUE FALSE
>> [57] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE
>> FALSE FALSE FALSE FALSE
>> [71] TRUE TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE FALSE
>> FALSE TRUE TRUE TRUE
>> [85] FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE FALSE
>> FALSE FALSE FALSE FALSE
>> [99] FALSE TRUE FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE
>>
>>> rle(a)
>> Run Length Encoding
>> lengths: int [1:29] 3 6 3 8 3 5 3 8 3 6 ...
>> values : logi [1:29] TRUE FALSE TRUE FALSE TRUE FALSE ...
>>
>> What should I do after this?
>>
>
> Well how about
>
> sum(a)
>
> or
>
> b <- rle(a)
> sum(b$lengths[b$values])
>
> Berend
>
>> Thanks,
>> Mike
>>
>> ______________________________________________
>> 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