TransWikia.com

In a list, find the numbers where they are bigger than the next numbers

Data Science Asked by Ellen Sheldon on August 21, 2020

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!

One Answer

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]

Answered by zachdj on August 21, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP