Fixed R Error Message: only 0’s may be mixed with negative subscripts

We all know that error messages are a nuisance. The good news is that if you are getting one it means you are probably writing real programs and not just little bits of code. The “only 0’s may be mixed with negative subscripts” error message looks hard at first but it is easy to understand.

The circumstances of this error.

This error message occurs when indexing a data structure using n:m where n and m are integers.

> x = 1:4
> x[-1:1]
Error in x[-1:1] : only 0’s may be mixed with negative subscripts

The error occurs when n is negative and m is positive. This the key to the problem and understanding, the error message, in this case, the error message makes perfect sense once you see what is causing it.

What is causing this error?

The reason this error occurs is that positive subscripts tell the program what to include in the resulting data structure, negative subscripts tell the program what to exclude.

> x = c(81,72,63,54)
> x
[1] 81 72 63 54
> x[2]
[1] 72
> x[-2]
[1] 81 63 54
> x[2:3]
[1] 72 63
> x[0:2]
[1] 81 72
> x[-2:0]
[1] 63 54
> x[-3:-2]
[1] 81 54

This little bit of code illustrates this by clearly showing what is missing. In this example, the first digit is the same as the integer position of the number. The second digit is there to show that it is not simply duplicating the index.

> x[-1:1]

When this configuration is used, where the first subscript is negative in the second subscript is positive, this is where we get our error message. The reason for this error message is that you are overlapping what you include and exclude from the resulting data structure.

How to fix this error.

Fixing this error is quite simple in that all you need to do is avoid the -n:m situation. You need to either make sure they are both negative, both positive, first one zero with second one positive, or first one negative with second one zero. It is a simple error to avoid.