[R] lines crosses
Peter Langfelder
peter.langfelder at gmail.com
Sat Apr 21 00:01:19 CEST 2012
On Fri, Apr 20, 2012 at 2:48 PM, Ben quant <ccquant at gmail.com> wrote:
>
> Hello,
>
> If the exact value does not exist in the vector, can I still get at the
> intersections? Is there a simple way to do this and avoid looping? Seems
> like there would be a simple R function to do this...
>
> Example:
> vec <- c(5,4,3,2,3,4,5)
> vec
> [1] 5 4 3 2 3 4 5
> intersect(vec,2.5)
> numeric(0)
>
> I want to get:
> 2.5 and 2.5
You want to get what? How many times the line crosses 2.5? That's easy:
vec = c(5,4,3,2,3,4,5)
query = 2.5
n = length(vec)
v1 = vec[-1]
v2 = vec[-n];
# this tells you where the line crosses your query going up
crossesUp = which(v2 < query & v1 > query)
# this tells you where the line crosses your query going down
crossesDown = which(v2 > query & v1 < query)
numberOfCrossings = length(crossesUp) + length(crossesDown)
HTH
Peter
More information about the R-help
mailing list