Flag positions in a vector number where values โ€‹โ€‹fall above or below a certain threshold

I'm not sure how to describe this question, so I'll just write some code to illustrate what I'm trying to achieve.

numberVector = c(56,23,10,26,11,9,33,60,71,1)
xaxisVector = c(1:length(numberVector))
booleanVector = c(FALSE,TRUE,FALSE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE,TRUE)
plot(xaxisVector,numberVector)
abline(a=50,b=0,col="red")
points(xaxisVector[booleanVector],numberVector[booleanVector],col="blue",pch=20)

      

As you can see, the above code creates a graph that looks like below.

As you can see, every time the value in numberVector goes from above 50 to below 50, I highlight the point in blue. (for example 56 to 23, 23 is highlighted) And every time the value in numberVector goes from below 50 to over 50, I highlight the point in blue. (e.g. 33 to 60, 60 stands out)

I manually typed boolean values โ€‹โ€‹into booleanVector. But how would I generate such a vector of booleans if there was any vector like numberVector?

Example graph

+3


source to share


1 answer


We can look at different signs of minus fifty. for example

booleanVector2 <- c(FALSE, diff(sign(numberVector-50))!=0)
all(booleanVector==booleanVector2)
# [1] TRUE

      



sign(x-50)

basically tracks if it is above or below the line. The diff()

difference between pairs of values โ€‹โ€‹for looking for changes is considered. We add FALSE because we assume the first value starts on one side of the string.

+1


source







All Articles