Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to function findInterval

Tags:

r

I'm using function findInterval to locate the position of another variables in the same row.

Example:

set.seed(123)
df <- data.frame(x=seq(1,10,1),y=rnorm(10,1))
val <- 0.5

df$x[findInterval(val,df$y, all.inside=TRUE)]

This give error, the vector must be sorted non-decreasingly

Is there an alternative? I have quite few columns and flipping columns back-and-forth is not that handy.

With re-ordering of course all works:

ordered.df <-df[order(df[ ,"y"], decreasing=FALSE), ]

ordered.df$x[findInterval(val,ordered.df$y, all.inside=TRUE)]
like image 463
Maximilian Avatar asked Feb 04 '26 20:02

Maximilian


1 Answers

I think you are looking for approx, with the constant method:

approx(x=df$y,y=df$x,xout=val,method="constant",yright=nrow(df)-1,yleft=1)$y

For the behaviour outside the interval, check the yleft and yright args.

like image 75
nicola Avatar answered Feb 08 '26 05:02

nicola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!