digit
digit

Reputation: 1523

Find if value is next value is bigger or smaller in R

I have the following R code:

y <-round(runif(100, min=0, max=800))
for(i in y) {
  if((i+1)>i) print("bigger") 
  if((i+1)<i) print("smaller")
}

I want to know if the next number in the list is bigger or smaller. It always prints bigger. I guess because I am doing it wrong. Any help would be great.. Thanks

Upvotes: 2

Views: 2723

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81713

You can create a vector in the following way:

c("smaller", "bigger")[(diff(y) > 0) + 1]

Upvotes: 4

Justin
Justin

Reputation: 43265

You can use diff for this.

yd <- diff(y)
ifelse(yd > 0, print('bigger'), print('smaller'))

The reason your for loop always prints bigger is because i is always less than i+1... look at what you're asking... you mean y[which(y==i) + 1] > i or something... If you must use a loop, you can do something like this:

for (i in seq_along(y)) {
  if (y[i+1] > y[i]) {
    print('bigger')
  } else {
    print('smaller')
  }
}

But, the vectorized version using diff will be much more efficient and easier to understand in my opinion.

Upvotes: 4

Related Questions