Shawn M.
Shawn M.

Reputation: 13

counting the larger value

Completely new to R and am trying to count how many numbers in a list are larger than the one right before.

This is what I have so far,

count <- 0
number <- function(value) {
for (i in 1:length(value)) 
  { if(value[i+1] > value[i])
  {count <- count + 1}
  }
}
x <- c(1,2,1,1,3,5)
number(x)

The output should be 3 based on the list.

Any help or advice would be greatly appreciated!

Upvotes: 1

Views: 44

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389055

A base R alternative would be diff

sum(diff(x) > 0)
#[1] 3

Or we can also eliminate first and last values and compare them.

sum(x[-1] > x[-length(x)])
#[1] 3

where

x[-1]
#[1] 2 1 1 3 5
x[-length(x)]
#[1] 1 2 1 1 3

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

You can lag your vector and count how many times your initial vector is greater than your lagged vector

library(dplyr)
sum(x>lag(x), na.rm = TRUE)

In details, lag(x) does:

> lag(x)
[1] NA  1  2  1  1  3

so x > lag(x) does

> x>lag(x)
[1]  NA  TRUE FALSE FALSE  TRUE  TRUE

The sum of the above is 3.

Upvotes: 1

Related Questions