9

I'm using a command to return the points at which participants reach 8 contiguous responses in a row. The command is:

 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 achieves 8 contiguous responses i'd like to set the variable "test" to equal -1. As it stands, the command returns integer(0) when 8 contiguous responses in a row are not found. I've tried writing an if command but can't seem to get it right.

Thanks in advance,

Will

1
  • 1
    Why not use logical TRUE and FALSE?
    – hadley
    May 15, 2011 at 3:46

2 Answers 2

15

If test is integer(0) then its length is 0. You can also coerce it to logical 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
3
  • 2
    Nice, but why not simply if (!length(test)) test <- -1 ?
    – kohske
    May 15, 2011 at 3:37
  • 2
    Or use any(rle(goo)$values==1 & rle(goo)$lengths >= 8).
    – hadley
    May 15, 2011 at 3:46
  • 2
    Or by following DRY principle: with(rle(goo), any(values == 1 & lengths >= 8))
    – aL3xa
    May 15, 2011 at 9:19
7

Combining @kohske and @hadley answers into one-liner you get

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.