I am using a function called curve_intersect under the package reconPlots to figure out whether two plotted lines intersect and what the intersection coordinates are. This is a link to the function: https://rdrr.io/github/andrewheiss/reconPlots/src/R/curve_intersect.R
Depending on what the line is, the function can throw an error if there are no points of intersection.
This is an example of a line which would throw an error:
line1 <- data.frame(x = c(1,2), y = c(1000,750))
line2 <- data.frame(x<-c(1,2,3,4), y = y<-c(60,90,800,1000))
curve_intersect(line1, line2)
And an example of one that would return the points of intersection:
line1 <- data.frame(x = c(1,2,3,4), y = c(1000,750,200,100))
line2 <- data.frame(x<-c(1,2,3,4), y = y<-c(60,90,800,1000))
curve_intersect(line1, line2)
I am writing a function where I would like to run a statement only if there is a point of intersection. i.e. I would like to run it if curve_intersect(line1, line2) does not throw an error.
Is there a simple way to run something only if it doesn't throw an error or is there another way I could run my code only if there is an intersection?
CodePudding user response:
You could use tryCatch()
. Here is an example which won't stop the code, but will print the error:
tryCatch(curve_intersect(line1, line2),
error = function(e) print(e))
To further answer your question, you could return NULL when the function fails. If the curve_intersect()
does not fail and does not return NULL, run what is inside the conditional statement:
c_i <- tryCatch(curve_intersect(line1, line2),
error = function(e) NULL)
if (!is.null(c_i)) {
fun()
}