0
$\begingroup$

I'm using Rstudio. I have a list like below, I want to find all the numbers that are bigger than the next numbers (i.e. numbers on their right hand, I make them bold).

7 7 9 9 9 10 10 1 51 51 53 58 58 58 58 59 59 62 64 67 0 0 3 3 12 12 12 1 4 4 5 5 9 21 25 25 27 27 29 33 33 49 50 0 0 0 3 4 4 8 8 8 21 21 21 21 21 24 25 25 26 27

Thanks anyone who kindly offers an idea!

$\endgroup$
2
  • $\begingroup$ Hi, please add a proper reproduceable example and format your code. $\endgroup$
    – Peter
    Nov 17, 2019 at 19:50
  • 1
    $\begingroup$ which(diff(x)<0) $\endgroup$
    – Valentas
    Dec 20, 2019 at 12:30

1 Answer 1

1
$\begingroup$

I think the following is the easiest and fastest way:

  1. Create a new vector with the "next neighbors"
  2. Subtract the "neighbors" vector from the original vector
  3. Determine which entries in the new vector are positive

I've actually never used R, but here's how I think it would work:

original_list <- c(7, 7, 9, 9, 9, 10, 10, 1, 51, 51)
# extract the "right neighbors" of the original list elements
neighbors <- original_list[-1]
# fill the missing position after the last element
neighbors <- append(neighbors, 0)
# compute the difference between the original vector and the right-neighbors
diff <- original_list - neighbors
# find the indices of positive elements
idx <- which(diff > 0)

# your output: elements which have a smaller right-neighbor
output <- original_list[idx]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.