Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading