If the command to check for an integer (0)

I use the command to return points at which participants reach 8 adjacent answers in a row. Team:

test <- which( rle(goo)$values==1 & rle(goo)$lengths >= 8) 

Where:

  goo <- c(1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0) 

if the participant never reaches 8 contiguous answers, I would like to set the variable "test" to -1. At its core, the command returns an integer (0) when 8 adjacent answers in the string are not found. I tried writing the if command, but it seems I don’t understand.

Thanks in advance,

Will

+8
r
source share
2 answers

Combining @kohske and @hadley answers in one liner, you get

 if(!any(test <- which(rle(goo)$values == 1 & rle(goo)$lengths >= 8))) test<- -1 
+7
source share

If the criterion is an integer (0), then its length is 0. You can also force it to a boolean with !

 length(test) 0 !(length(test) TRUE # and would be FALSE for any vector with normal length > !(length( c(1,2,3) )) [1] FALSE 

So:

 > if ( !length(test) ) {test<- -1} > test [1] -1 
+14
source share

All Articles