[R] confusion with R syntax
Mark Wardle
mark at wardle.org
Thu Oct 11 22:18:12 CEST 2007
On 11/10/2007, Leeds, Mark (IED) <Mark.Leeds at morganstanley.com> wrote:
> I just noticed something by accident with R syntax that I'm sure is
> correct but I don't understand it. If I have
> a simple numeric vector x and I subscript it, it seems that I can then
> subscript a second time with TRUE
> or FALSE, sort of like a 2 dimensional array in C. Does someone know if
> this is documented somewhere
> Because it's neat but I never knew it existed. To me it seems like a 1
> dimensional vector should
> have only one dimensional indexing ?
>
> x <- seq(1,10)
> > x
> [1] 1 2 3 4 5 6 7 8 9 10
> > x[2:4][c(TRUE,FALSE,TRUE)]
> [1] 2 4
>
> But, it only works for TRUE or FALSE and not numbers so I think it's not
> really 2 dimensional indexing.
>
> x[1][2]
>
> [1] NA
>
> If someone could explain this mechanism or tell me what I should look
> for in the archives, it would
> be appreciated. Thanks.
I may be being naive, but it is much simply than you are trying to
make it. Aren't the two indexing operations run in sequence?
Therefore
x[2:4][c(TRUE,FALSE,TRUE)]
actually is interpreted in two steps. Try this:
x <- seq(1,10)
y <- x[2:4]
z <- y[c(TRUE, FALSE, TRUE)]
Indeed, while your code:
x[1][2]
doesn't work,
if you try
x[2:4][3]
then you get the third index of the vector created by 2:4
ie
y <- x[2:4]
z <- y[3]
Best wishes,
Mark
--
Dr. Mark Wardle
Specialist registrar, Neurology
Cardiff, UK
More information about the R-help
mailing list