HollowBastion
HollowBastion

Reputation: 223

Flagging positions in a number vector where values fall above or below a certain threshold

I'm not sure how to describe this question, so I'm just going to write a bit of code here 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 produces a graph that looks like below.

As you can see, every time the value in the numberVector goes from a value above 50 to a value below 50, I highlight the dot in blue. (e.g. from 56 to 23, 23 is highlighted) And likewise every time the value in the numberVector goes from a value below 50 to above 50, I highlight the dot in blue. (e.g. from 33 to 60, 60 is highlighted)

I've manually typed the booleans in booleanVector. But how would I generate such a vector of booleans given any vector like numberVector?

Example graph

Upvotes: 3

Views: 41

Answers (1)

MrFlick
MrFlick

Reputation: 206243

We can look at the different in the signs of the minus fifty. For example

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

The sign(x-50) basically keeps track if its above or below the line. The diff() looks at the difference between pairs of values to look for changes. We add in a FALSE since the we assume the first value starts on one side of the line.

Upvotes: 1

Related Questions