2

I am having trouble which what I thought would be a simple issue.

I have the following vector (which is actually a column in a dataset)

example_data <- c(1, 2, 3, 4, 5, 6, 7, 8, 5, 9, 4, 5, 4, 5, 6, 5, 3, 3, 2, 4, 5, 6, 4, 5, 6, 6, 5)

I want to find the number of times that c(4, 5, 6) occurs, exactly in that order. In the above example this would be 4 times.

I have attempted using %in% and grepl() but neither of those have proved successful. I have also tried collapsing the vector into one sequence and matching that way but no luck.

I just feel like I am missing something very obvious, so any help would be greatly appreciated.

FitzKaos
  • 381
  • 3
  • 20
  • @akrun unfortunately that just gives me the number of times 4, 5 and 6 occur, regardless of order. – FitzKaos Nov 29 '18 at 20:25
  • 1
    Yeah, i realized that, so I corrected in the solution – akrun Nov 29 '18 at 20:26
  • 1
    Related: [Get indexes of a vector of numbers in another vector](https://stackoverflow.com/questions/48660606/get-indexes-of-a-vector-of-numbers-in-another-vector?noredirect=1&lq=1), [Matching a sequence in a larger vector](https://stackoverflow.com/questions/16244006/matching-a-sequence-in-a-larger-vector), [Match a vector inside a vector](https://stackoverflow.com/questions/50612584/match-a-vector-inside-a-vector), [R: find indexes of vector in another vector (if it exists)](https://stackoverflow.com/questions/53303614/r-find-indexes-of-vector-in-another-vector-if-it-exists) – Henrik Nov 29 '18 at 20:33

1 Answers1

3

One method is to get the lead of the values with shift (from data.table) into a list, then Reduce it to a logical vector after comparing with the values of interest 4, 5, 6, and get the sum of TRUE elements

library(data.table)
sum(Reduce(`&`, Map(`==`, shift(example_data, 0:2, type = 'lead'), 4:6)))
#[1] 4

or paste the data into a string and with str_count from stringr get the count of the pattern '456'

library(stringr)
str_count(paste(example_data, collapse=""), '456')
#[1] 4
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Brilliant! Works well! Though I need to study that first method a bit to ensure I understand it! :p I like the str_count method - more intuitive to me. And I think that was where I was trying to get. Thanks for your help! – FitzKaos Nov 29 '18 at 20:27
  • 3
    In base R you could use: `regexpr("456",paste(example_data,collapse = ""))[1]` – Brian Davis Nov 29 '18 at 21:08