To see where your function y=f(x) (which I assume to be continuous) intersects a horizontal line y=h, you can look for sign changes in f(x)-h. The locations where this sign changes are locations where the function crosses the line. Unless you know more details about your function, so that you can interpolate between data points, this is probably the best you can hope for.
To compute sign changes in R, you can use code like this:
h <- 1000
d <- y - h
signChanges <- (d[1:(length(d)-1)] * d[2:length(d)]) <= 0
The resulting array will have one less element than your x
array, as each element corresponds to an interval between two adjacent x
values. If you have a data point exactly on the line, then the array will contain two subsequent TRUE
values. If this is a problem, then you could insert
d <- ifelse(d == 0, 1, d)
which moves the data points slightly off the line.
To obtain corresponding x
values, you can use the center of each interval:
x2 <- (x[c(signChanges, FALSE)] + x[c(FALSE, signChanges)])/2
Or you could perform a linear interpolation between the two adjacent data points:
left <- c(signChanges, FALSE)
right <- c(FALSE, signChanges)
t <- (h - y[left])/(y[right] - y[left])
x2 <- (1 - t)*x[left] + t*x[right]