[英]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. cummax()
您可以使用cummax()
来获得最大值。 x >= cummax(x)
basically gives you the answer, although element 1 is TRUE
, so you just need to change that: x >= cummax(x)
基本上给出了答案,虽然元素1为TRUE
,所以你只需要改变它:
> out = x >= cummax(x)
> out[1] = NA
> out
[1] NA TRUE FALSE TRUE FALSE
Although @Marius has got this absolutely correct. 虽然@Marius有这个绝对正确的。 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 或者与显式
for
循环相同的逻辑
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
我们可以使用
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
max.col(t(sapply(x, `>=`, x)), 'last') > seq_along(x)
#[1] FALSE TRUE FALSE TRUE FALSE
or with for
loop 或者使用
for
循环
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]))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.