Skip to content

Fastest way of finding if any members of vector x fall in the range of the rows of matrix y

12 messages · Dimitris Rizopoulos, PIKAL Petr, Dennis Murphy +4 more

#
One approach is the following:

x <- rnorm(5)
y <- matrix(rnorm(5*2), 5, 2)

check <- y - x
check[, 1] * check[, 2] < 0


I hope it helps.

Best,
Dimitris
On 6/24/2011 10:57 AM, Salih Tuna wrote:

  
    
#
Hi
to
will
one.
Can you explain what is probe and what is region and how Dimitri's code 
failed to do what you wanted?

Only if x is between y values you get one number in check negative and one 
positive and their multiplication is therefore lower than zero.

Regards
Petr
the
http://www.R-project.org/posting-guide.html
#
Hi:

That leaves open several possibilities. Could you please supply a
small, reproducible example (i.e., one that someone can copy and paste
into an R session) that illustrates the problem along with the
solution you expect?

TIA,
Dennis
On Fri, Jun 24, 2011 at 2:30 AM, Salih Tuna <salihtuna at gmail.com> wrote:
#
On 2011-06-24 09:52, Salih Tuna wrote:
Probably not faster, but try:

   x <- c(1,2,6,5)
   y <- matrix( c(1,3,8,4,5,10), 3, 2 )
   ok <- vector( 'logical', length(x) )
   for( i in seq_along(x) ) ok[i] <- any( apply(y - x[i], 1, prod) <= 0 )
   x[ok]

Peter Ehlers
#
Hi:

Not much different from Peter's approach, but here's another try:

v <- c(1, 2, 6, 5)
w <- matrix(c(1, 4, 3, 5, 8, 10), ncol = 2, byrow = TRUE)
[,1] [,2]
[1,]    1    4
[2,]    3    5
[3,]    8   10


f <- function(x) v[which(v >= x[1] & v <= x[2])]
unlist(apply(w, 1, f))
[1] 1 2 5

If you just do the apply() part, the function will return a list of
those elements of v that fall within the i-th interval.

HTH,
Dennis
On Fri, Jun 24, 2011 at 9:52 AM, Salih Tuna <salihtuna at gmail.com> wrote:
#
On 06/24/2011 11:12 AM, Dennis Murphy wrote:
Maybe

 > v = c(1, 2, 6, 5)
 > start = c(-Inf, 1, 3, 8)
 > end = c(-Inf, 4, 5, 10)
 > v[ v <= end[findInterval(v, start)] ]

Also IRanges::findOverlaps / countOverlaps in Bioconductor

   v[countOverlaps(IRanges(v, v), IRanges(start, end)) != 0]

http://bioconductor.org/install

Martin

  
    
#
yet another solution is:

v <- c(1, 2, 6, 5)
w <- matrix(c(1, 4, 3, 5, 8, 10), ncol = 2, byrow = TRUE)

check <- outer(w[, 1], v, "-") * outer(w[, 2], v, "-")
v[which(check <= 0, arr.ind = TRUE)[, 2]]


Best,
Dimitris
On 6/24/2011 10:05 PM, Martin Morgan wrote:

  
    
2 days later
#
try sqldf:
x
1 1
2 2
3 6
4 5
s  e
1 1  4
2 3  5
3 8 10
+     select x.x
+         from x, y
+         where x.x between y.s and y.e
+ ")
  x
1 1
2 2
3 5

        
On Mon, Jun 27, 2011 at 5:33 AM, Salih Tuna <salihtuna at gmail.com> wrote: