r - Which vector posseses the nearest lower value? -


goal

given 3 vectors a, b , x, vector sol stating true every time nearest lower value of a , b united comes a , false if comes form b.

information data

  • a relatively short (~80 elements) vector of integers.
  • b relatively short (~200 elements) vector of integers.
  • x long (1e7-1e8 maybe) vector of integers.

example data

these data shorter 1

set.seed(31) while(true) {    = floor(runif(30, 1,1e5))    b = c(1,floor(runif(80, 1,1e5)))    if (!any(c(a %in% b, b %in% a))){break} } x = floor(runif(300, 1,1e5)) 

non-performent solution

the following should work slow x become long.

sol = rep(na,length(x)) (i in 1:length(x)) {    xi = x[i]    ma = max(a[a<=xi])    mb = max(b[b<=xi])    if (ma>mb) {sol[i]=true} else {sol[i]=false} } 

note on performance

the process repeated maybe 1000 times. don't have accurate estimation of number of repeats , length of x though.


benchmark @marattalipov answer in comparison mine

set.seed(31) while(true) {    = floor(runif(100, 1,1e6))    b = c(1,floor(runif(300, 1,1e6)))    if (!any(c(a %in% b, b %in% a))){break} } x = floor(runif(1e5, 1,1e6))   marat = function (a,b,x) {     d <- rbind(data.frame(x=true,y=a),data.frame(x=false,y=b))     d <- d[order(d$y),]     return (d$x[findinterval(x,d$y)]) } remi = function (a,b,x) {     sol = rep(na,length(x))     (i in 1:length(x))     {        xi = x[i]        ma = max(a[a<=xi])        mb = max(b[b<=xi])        if (ma>mb) {sol[i]=true} else {sol[i]=false}     } }   benchmark(s1 <- marat(a,b,x), s2 <- remi(a,b,x), order="elapsed")                 test replications elapsed relative user.self sys.self user.child sys.child 1 s1 <- marat(a, b, x)       100   1.003       na     0.964    0.065          0         0 2 s2 <- remi(a, b, x)        100 144.118       na   130.320   14.867          0         0 

how approach:

d <- rbind(data.frame(x=true,y=a),data.frame(x=false,y=b)) d <- d[order(d$y),] out <- d$x[findinterval(x,d$y)] 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -