r - find contiguous responses greater than x -
i'm trying find the point @ participants reach 8 contiguous responses in row greater 3. example:
x <- c(2,2,4,4,4,4,5,5,5,5,7)
i want return value 10.
i tried code (thanks @dwin):
which( rle(x)$values>3 & rle(x)$lengths >= 8) sum(rle(x)$lengths[ 1:(min(which(rle(x)$lengths >= 8))-1) ]) + 8
the problem above code works if responses identical , greater 3. code returns zero.
if:
x <- c(2,2,4,4,4,4,4,4,4,4,7)
the code works fine. isn't how data looks.
thanks in advance!
why don't create new vector contains identical values rle
needs work properly? can use ifelse()
, put function:
fun <- function(x, value, runlength) { x2 <- ifelse(x > value, 1, 0) ret <- sum(rle(x2)$lengths[ 1:(min(which(rle(x2)$lengths >= runlength))-1) ]) + runlength return(ret) } > fun(x, value = 3, runlength = 8) [1] 10
Comments
Post a Comment