0

I need a good vectorization on b of this function:

match(TRUE, b <= a)

For example:

 # EDIT
 a <- c(2,3,5,6,7,8,10,12) #edited
 b <- c(1,3,11)
 #output should be: 1 2 8
 findInterval(b,a) + 1 # 1 3 8
 findInterval(b,a) + 1 - ifelse(!is.na(match(b,a)),1,0) # 1 2 8

EDIT:

findInterval(b,a) + 1 is a partial answer, it works only if the test is b < a. But i need b <= a. My guess is : findInterval(b,a) +1 - ifelse(!is.na(match(b,a)),1,0), but i would like a better version of ifelse(!is.na(match(b,a)),1,0) or a better answer.

vrige
  • 297
  • 1
  • 9

1 Answers1

3

You can use cut/findInterval :

findInterval(b, a) + 1
#[1] 1 2 8

Using cut :

cut(b, c(-Inf, a), labels = FALSE)
#[1] 1 2 8

If we also want to match on borders we can use left.open = TRUE.

findInterval(b,a, left.open = TRUE) + 1
#[1] 1 2 8
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • In general, your first solution doesn't work. I tried this:`b1 <- array(-1, dim = 10)` `b2 <- array(-1, dim = 10)` `a <- sort(sample(1:200, 100))` `b <- sample(1:200, 10)` `for(i in seq(1, length(b))){` `b1[i] <- match(TRUE, b[i] <= a)` `}` `b2 <- findInterval(b,a) + 1` b1 is different from b2 – vrige Jun 09 '20 at 11:20
  • it works only when the test is `b < a` – vrige Jun 09 '20 at 11:47
  • `findInterval(b,a) + 1 -ifelse(!is.na(match(b,a)),1,0)` – vrige Jun 09 '20 at 12:00
  • 1
    @vrige Can you update your post with the example. It is difficult to copy/paste your example from comments. – Ronak Shah Jun 09 '20 at 12:02
  • 1
    @vrige See updated answer. We need to include `left.open = TRUE`. – Ronak Shah Jun 09 '20 at 12:42
  • @vrige Also I see that `cut` already gives you the expected output. – Ronak Shah Jun 09 '20 at 13:00