简体   繁体   中英

How to find number of observation between first observation and first two consecutive negative observations in r

I have a large data frame and I need a function to automate this search. Basically I want to find how many observations are between the first observation and the first two consecutive negative observations.

Example:

x <- c(2, 1, 9, 3, 4, -6, 5, 6, -7, -1)

Assuming that this is my data I want to count the number of data points between 2 and -7.

I need to do this in r.

Help is highly appreciated:D !!!

You can do:

which.max(cumsum(x < 0) == 2)

[1] 9

You can use rle to find the first two consecutive negative observations like:

i <- rle(!(is.na(x) | x>=0))
j <- i$lengths > 1 & i$values
j <- if(any(j)) min(which(j))-1 else 0
if(j > 0) sum(i$lengths[seq_len(j)])-1 else 0
#[1] 7

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