1

Hopefully a simple question:

I am getting an "argument is of length zero" for the if statement line:

for (i in 1:(length(MixedDF))) {
      if (MixedDF[i,1] - MixedDF[i-1,1] == 1) {
      SwitchInd[i] = MixedDF$trial[i]
  }
}

Where MixedDF is a large matrix and SwitchInd is a matrix of zeroes that is supposed to get filled in with the indices identified in the if statement. MixedDF$trial or MixedDF[i,1] is the first column in the matrix. This column contains integers starting at 51 and going to 74, where there are many rows with the same value. So for example MixedDF$trial <- c(51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53.....). I want to identify the indices where the trial changes, so 51 to 52, 52 to 53 and so on. More generally I want to understand why the if statement isn't working, it seems straightforward.

Jaap
  • 81,064
  • 34
  • 182
  • 193
bsils
  • 25
  • 6
  • 1
    When `i` is `1`, `MixedDF[i-1,1]` is not well formed. – nrussell Dec 02 '16 at 17:08
  • A [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610) would be nice. This makes it a lot easier for others to help you. – Jaap Dec 02 '16 at 17:11
  • using which I get an "argument to 'which' is not logical. I had set MixedDF$trial to as.numeric, not sure if that matters. – bsils Dec 02 '16 at 17:42
  • Yes Ronak, sorry for the confusion. – bsils Dec 02 '16 at 17:50
  • numeric. However, this does work: which(MixedDF$trial[-1] != MixedDF$trial[-length(MixedDF$trial)]) – bsils Dec 02 '16 at 17:53

2 Answers2

2

This gives the indices where the value changes

x <- c(51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53)
which(diff(x)!= 0) + 1 

#[1]  6 15
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    Thanks this works when class is appropriate and is simple; also found this to work: which(MixedDF$trial[-1] != MixedDF$trial[-length(MixedDF$trial)]) but could not get the for loop to work. – bsils Dec 02 '16 at 18:03
0

Make sure you don't have NULL values. Also, you are not defining the cases where the if statement fails. Add an 'else' condition.

if (MixedDF[i,1] - MixedDF[i-1,1] == 1) 
{
    SwitchInd[i] = MixedDF$trial[i]
}
else
{
    SwitchInd[i] = SOME VALUE
}

Another problem is you can't start from 1 (when i is 1, i-1 is 0).

Brian O'Donnell
  • 1,836
  • 19
  • 29