Paul
Paul

Reputation: 323

How to write a R code for determining a value is above a line or below a line?

I want to write a R code as follows:

Give a function say y = xb + c where b and c are constants. I want to determine a horizontal interval say (alpha, beta) lies above the function, below the function or intersect the function. (See uploaded plot) Plot of the function and line

I find myself cannot figure out how to code this programming in R.

Would someone help me out.

Upvotes: 0

Views: 112

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

You didn't mention that you also need to specify a y value for the horizontal range, which I assume in my answer. A given horizontal range intersects the line y = xb + c if y(x.min) is below the y value of the line, and y(x_max) is above the y value of the line. Here x.min is the start of the range and x.max is the end of the range.

intersect <- function(x.min, x.max, y, b, c) {
    y.min <- x.min * b + c
    y.max <- x.max * b + c

    if (y.min <= y & y.max >= y) {
        print("intersection")
    }
    else if (y > y.min) {
        print("above")
    }
    else {
        print("below")
    }
}

Note:

This answer assumes that the line has a positive slope. If the line also might have a negative slope, then there is a second criteria for intersection, so the if statement would look like this:

if ((y.min <= y & y.max >= y) | (y.min >= y & y.max <= y)) {
    print("intersection")
}

Upvotes: 2

Related Questions