Home > front end >  how to find the first and the last value that has different trend in a trend that keeps the same?
how to find the first and the last value that has different trend in a trend that keeps the same?

Time:12-01

I would like to know: if B becomes bigger than A, get the first value of B that is bigger than A (if B keeps bigger than A, it would not count until B becomes smaller than A) in the trend, and after that, if B becomes small than A, then get first value of B that is smaller that A (if B keeps smaller than A, it would not count, until B becomes bigger than A ). My code below that does not work:

>A
[1] 1 2 3 4 5 8 10 15
>B
[1] 0 3 5 3 6 11 14 13
fn<-function(m,n){
count<-0
for (i in 1:length(m)){
  for (j in i 1: length(m) 1){
    if((m[i]<n[i]&&m[j]>n[j])||(m[i]>n[i]&&m[j]<n[j])){
        count<-count 1
    }
  }
}
}
fn(A,B)

the output should be (3 > 2, count: 1; 3 < 4, count: 2; 6 > 5, count: 3, 13 < 15, count: 4):

>count
4

CodePudding user response:

Try something like this:

d <- sign(A - B)
sum(head(d, -1) * tail(d, -1) < 0)

trying to catch how many times sign changes in adjacent positions of difference.

if you are interested in positions then you can do:

s <- which(head(d, -1) * tail(d, -1) < 0) 
s <- s   if(length(s) > 0) 1
A_ <- A[s]
B_ <- B[s]
count <- length(s)
  •  Tags:  
  • r
  • Related