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)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With