[R] Odd behaviour of subset indexing (x:y).

Marc Schwartz marc_schwartz at comcast.net
Wed Jan 21 00:10:25 CET 2009


on 01/20/2009 05:01 PM John Sorkin wrote:
> R 2.8.1
> windows XP
> 
> I don't understand the output from x[iS+1:iE] produced by the code below:
> 
> x = c(1,2,3,4,5)
> x
>  [1] 1 2 3 4 5
> 
>  iS=2   #  start position
>  iE=4   #  end position
> 
> [iS:iE]
> [1] 2 3 4
> 
> # I don't understand the results of the command below. I would expect to see 3, 4, not 3, 4, 5, NA
> x[iS+1:iE]
> [1]  3  4  5 NA
> 
> Thanks,
> John

Operator precedence.

Note:

# You are asking for indices 3:6 and of course x[6] does not exist
# hence the NA
# Equivalent to: iS + (1:iE)

> iS + 1:iE
[1] 3 4 5 6


# This is what you want
> (iS + 1):iE
[1] 3 4


HTH,

Marc Schwartz




More information about the R-help mailing list