简体   繁体   中英

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

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

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

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

We can use lapply

unlist(lapply(seq_along(x), function(i) all(x[i] >=x[seq(i)])))
#[1]  TRUE  TRUE FALSE  TRUE FALSE

Or with max.col

max.col(t(sapply(x, `>=`, x)), 'last') > seq_along(x)
#[1] FALSE  TRUE FALSE  TRUE FALSE

or with for loop

mx <- x[1]
i1 <- logical(length(x))
for(i in seq_along(x)) {i1[i][x[i] > mx] <- TRUE; mx <- max(c(mx, x[i]))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM