rose
rose

Reputation: 1981

Check which elements of a vector is between the elements of another one in R

I am new user in R. How can I check which elements of the vector A is between the elements of vector B for example:

    A = c(1.1, 3.2, 5, 8.5, 4.6, 2.2)
    B = c(1, 2, 3)

means that which elements of A is between 1 and 2 , then which elemets of A is between 2 and 3?

Upvotes: 2

Views: 186

Answers (4)

Glen_b
Glen_b

Reputation: 8252

Try this:

      data.frame(A,cut(A,B))

For each observation in A, it tells you which pair of B observations it's between.

Like so:

> data.frame(A,cut(A,B))
    A cut.A..B.
1 1.1     (1,2]
2 3.2      <NA>
3 5.0      <NA>
4 8.5      <NA>
5 4.6      <NA>
6 2.2     (2,3]

NA means it isn't between two B observations.

Also try:

data.frame(A,cut(A,c(-Inf,B,Inf)))

Upvotes: 0

Tyler Rinker
Tyler Rinker

Reputation: 109844

If I understand correctly this is one possibility:

A = c(1.1, 3.2, 5, 8.5, 4.6, 2.2)
B = c(1, 2, 3,4,10)

B1 <- head(B, -1)
B2 <- tail(B, -1)

outs <- list()

for(i in seq_along(B1)) {
    outs[[i]] <- A[B1[i] < A & A < B2[i]]
}

names(outs) <- paste(B1, " & ", B2)

## > outs
## $`1  &  2`
## [1] 1.1
## 
## $`2  &  3`
## [1] 2.2
## 
## $`3  &  4`
## [1] 3.2
## 
## $`4  &  10`
## [1] 5.0 8.5 4.6

Upvotes: 1

mnel
mnel

Reputation: 115382

You want some variant of findInterval

findInterval(A,B)
[1] 1 3 3 3 3 2

Value 1 indicates it is between 1 and 2 (the lowest and next lowest value in B) Value 2 indicates it is between 2 and 3

So to find which ones are between

which(findInterval(A,B) %in% seq_len(length(unique(B))-1))
# [1] 1 6

and to extract from A

A[findInterval(A,B) %in% seq_len(length(unique(B))-1)]

# [1] 1.1 2.2

You could also use cut, which will create a factor.

In conjunction with split this will give

 split(A, cut(A,B),drop=FALSE)
$`(1,2]`
[1] 1.1

$`(2,3]`
[1] 2.2

Upvotes: 3

Santhosh
Santhosh

Reputation: 1791

I have assumed that it is going to be consecutive numbers in B for which you will be checking

result.pair<-matrix(rep(integer(), 3), ncol = 3)
colnames(result.pair)<-c("B1", "A", "B2")
for(i in 1:(length(B)))
{
  for(j in 1:(length(A)))
  {
    if ((B[i] <= A[j])  & (B[i+1] >= A[j]))
    {
      result.pair<-rbind(result.pair, c(B[i], A[j], B[i+1]))
    }
  }

}

result.pair

Upvotes: 1

Related Questions