0

I have seen many methods in order to get the number or to find value in vector or even many values such as : which(a %in% c(2,3))

But the problem is that don't respect the order of my vector [2 3], I look for the vector but not every element separately .

Do you have a solution please?

Thanks

EntrustName
  • 421
  • 6
  • 19
  • Could you please clarify what is implied by "don't respect the order"? `which()` does return the matching indici, which are in order by the definition of vector. Second, what is `a`, scalar value or also a vector? – Maxim.K May 08 '13 at 08:09
  • hi, if you could please post an example of `a` (And perhaps an example of what you would like the output to look like) that would be helpful in understanding the question – Ricardo Saporta May 08 '13 at 08:11
  • Ok sorry, `a` is a vector as `sample(1:6, 12, TRUE) : [1] 3 6 6 2 3 2 6 3 5 4 5 2` and I'm looking for the sequence [2, 3] in `a` but not every 2 and every 3 – EntrustName May 08 '13 at 08:22

4 Answers4

1

If all of the values in your vector are single digit, you could use: gregexpr("23",paste0(a,collapse="")) to return the position of the 2 in every c(2,3) sequence.

Thomas
  • 43,637
  • 12
  • 109
  • 140
1

grep("2|3",paste(a,collapse="|")) I think some separators like "|" may be better for perplexing situation

pudding
  • 76
  • 4
0

For simple cases, you can construct a 2-row matrix and compare every column with your query vector, and then find the index of column which is true in every row.

which(colSums(rbind(a[1:11],a[2:12]) == c(2,3)) == 2)
cogitovita
  • 1,685
  • 1
  • 15
  • 15
0
set.seed(0)
a <- sample(1:6,12000, TRUE)
b <- 2:4

vecIn <- function(a,b){
which(
Reduce('+', lapply(seq_along(y <- lapply(b, '==', a)), function(x){
                                            y[[x]][x:(length(a) - length(b) +x)]
                                           }
                  )
      ) == length(b)
     )
} 

> vecIn(a,b)
 [1]     2   154   986  1037  1046  1257  1266  1750  2375  2677  3184  3206
[13]  3499  3526  3882  4238  4311  4388  4437  4580  4714  4766  4827  5046
[25]  5279  5629  6153  6842  6856  6919  7200  7516  7520  7707  7824  7859
[37]  8140  8191  8687  9208  9281  9313 10022 10320 10617 10720 10958 11179
[49] 11567 11591 11698 11811

library(zoo)
library(rbenchmark)

func1 <- function(a,b){
 gregexpr(paste0(b,collapse=""),paste0(a,collapse=""))
}

func2 <- function(a,b){
 which(rollapply(a, length(b), identical, b))
}

func3 <- vecIn

Some benchmarks

benchmark(func1(a,b), func2(a,b), func3(a,b))
         test replications elapsed relative user.self sys.self user.child
1 func1(a, b)          100   0.673    5.904     0.680    0.000          0
2 func2(a, b)          100  28.808  252.702    28.198    0.672          0
3 func3(a, b)          100   0.114    1.000     0.116    0.000          0
  sys.child
1         0
2         0
3         0
user1609452
  • 4,406
  • 1
  • 15
  • 20