Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to find if a value is greater than all prior values in a vector

Tags:

r

This should be very simple, but my r knowledge is limited. I'm trying to find out if any value is greater than all previous values. An example would be

x<-c(1.1, 2.5, 2.4, 3.6, 3.2)

results:

NA  True False True False

My real values are measurements with many decimal places so I doubt I will get the same value twice

like image 636
Raaaa Avatar asked Jun 24 '19 05:06

Raaaa


2 Answers

You can use cummax() to get the biggest value so far. x >= cummax(x) basically gives you the answer, although element 1 is TRUE, so you just need to change that:

> out = x >= cummax(x)
> out[1] = NA
> out
[1]    NA  TRUE FALSE  TRUE FALSE
like image 75
Marius Avatar answered Oct 13 '22 19:10

Marius


Although @Marius has got this absolutely correct. Here is an option with a loop

sapply(seq_along(x), function(i) all(x[i] >= x[seq_len(i)]))
#[1]  TRUE  TRUE FALSE  TRUE FALSE

Or same logic with explicit for loop

out <- logical(length(x))
for(i in seq_along(x)) {
   out[i] <- all(x[i] >= x[seq_len(i)])
}
out[1] <- NA
out
#[1]    NA  TRUE FALSE  TRUE FALSE
like image 24
Ronak Shah Avatar answered Oct 13 '22 20:10

Ronak Shah