简体   繁体   中英

Finding extreme values in vector elements in R

I have a vector like this:

x<-c(-0.193,-0.126,-0.275,-0.375,-0.307,-0.347,-0.159,-0.268,-0.013,0.070,0.346,
0.376,0.471,0.512,0.291,0.554,0.185,0.209,0.057,0.058,-0.157,-0.291,-0.509,
-0.534,-0.239,-0.389,0.060,0.250,0.279,0.116,0.052,0.201,0.407,0.360,0.065,
-0.167,-0.572,-0.984,-1.044,-1.039,-0.831,-0.584,-0.425,-0.362,-0.154,0.207,
0.550,0.677,0.687,0.856,0.683,0.375,0.298,0.581,0.546,0.098,-0.081)

I would like to find the position of the lowest number each time >=5 consecutive values are <-0.5. In the example that is the value -1.044 .

How do I find this?

What I have done is this:

xx<-ifelse(x>.5,1,NA)
xx

aa<-rle(xx)
zz <- rep(FALSE, length(xx))
zz[sequence(aa$lengths) == 1] <- aa$lengths >= 5 & aa$values == 1
zz

But then I just find the position of the first value and not the extreme.

Any help?

Thanks for posting what you've tried.

I'd just use a logical comparison for xx :

xx <- x < -0.5

Then your rle logic becomes:

aa <- rle(xx)
zz <- aa$lengths >= 5 & aa$values

From there, identify which values of zz are true and use cumsum to get the indicies of x (this is oversimplified since there is only once instance but you get the picture):

first <- which(zz)
idxs <- cumsum(aa$lengths[1:first])
min(x[idxs[first-1]:idxs[first]])

In the instance where you have multiple matches, first will be a vector with length > 1. In that case, make a function and you can apply it to your vector:

myfun <- function(y) {
    idxs <- c(0, cumsum(aa$lengths[1:y]))
    min(x[idxs[y]:idxs[y+1]])
}

set.seed(20)
x <- rnorm(100)
xx <- x < -0.5
aa <- rle(xx)
zz <- aa$lengths >= 3 & aa$values
first <- which(zz)

sapply(first, myfun)

A function with the apply function inside:

find.val <- function(x,threshold,n,all=T){
  tmp <- rle(x < threshold)
  cs <- cumsum(tmp$lengths)
  dfcs <- data.frame(indices=c(0,cs[-length(cs)])+1,l=cs)
  pos <- (apply(dfcs,1,function(y) which.min(x[y[1]:y[2]])+y[1]-1))[tmp$values==1 & tmp$lengths >= n]
  if(all==T) return(pos)
  pos[which.min(x[pos])]

}

if you set all=T you get all matches otherwise only the position of the lowest match. Example:

find.val(x,-0.5,5,all=T)

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