Search code examples
rloess

Finding x for f(x) loess function


I have a couple of loess models using similar data to....

set.seed(123)

y<-(runif(100,-20,20))
z<-seq(-12.75,12,.25)*rnorm(100,1,3)
x<-seq(1,100,1)
df<-data.frame(cbind(y,x,z))
model <- loess(y ~ x, data = df)
model2<-loess(z~x,data=df)

What I am trying to accomplish (without any luck) is to identify where the smoothed lines do 2 things:

1) I want to identify at what value(s) of x do the lines cross y=0

2) I want to identify at what value(s) of x the 2 loess lines cross each other.

I've been looking for similar problems and solutions to those problems for too long now with no success. Any help would be greatly appreciated.

ggplot(df,aes(x=x,y=y))+
  geom_point()+
  geom_smooth(method="loess",se=F)+
  geom_smooth(aes(y=z),method="loess",se=F)

Solution

  • You can use predict to get y value for any x, and then optimise to find the specific x value that solves for the y value you want.

    For example, to find the zero crossing of model, we can optimise to find where the square of its fitted value is a minimum

    zero1 <- optimize(function(x, m) predict(m, x)^2, range(x), model) 
    # 
    # $minimum
    # [1] 67.89191
    

    Note that this will only find a single local minimum. If your model crosses zero several times, you will need to solve like this in each of the ranges where there is a zero (by changing the second argument of optimize, which specifies the range to search within).

    Exactly the same approach can find where the models intersect. For that case you minimise the square of the difference between the two models:

    intersection <- optimize(function(x, m1, m2) (predict(m1, x) - predict(m2, x))^2,
                  range(x), model, model2)  
    # $minimum
    # [1] 45.65295