[R] an issue about subsetting a vector

Ben Bolker
Sun, 24 Mar 2024 18:30:25 -0000

As with a lot of things in R, the behaviour is counterintuitive but
(arguably) logical. The key (maybe) is that `a[-x]` does not mean "take
all of the elements of a except those indicated by `x`, but rather,
"negate x, then take all but the negative elements".  In other words,

  -integer(0)  is   integer(0)  (we multiply *each of the elements of
integer(0)* by -1, but integer(0) has no elements)

   that reduces to a[integer(0)]

and from there you get "select none of the elements".

   A related point is explained in the R Inferno
https://www.burns-stat.com/pages/Tutor/R_inferno.pdf section 8.1.13,
"negative nothing is something".

   See also

https://stackoverflow.com/questions/42615728/subsetting-vector-how-to-programatically-pass-negative-index-safely

https://stackoverflow.com/questions/40026975/subsetting-with-negative-indices-best-practices/40029485#40029485

On 2024-03-24 2:19 p.m., Paulo Barata wrote:
>
> To the R-Help list,
>
> I would like to have a clarification about an issue that I observe when
> subsetting a vector. This is R version 4.3.3 on Windows 10.
>
> -- Example with a vector:
>
>  > a <- 1:5
>  > a
> [1] 1 2 3 4 5
>
> So we have, with a negative index:
>  > a[-3]
> [1] 1 2 4 5
>
> But when the index is integer(0), we have this:
>
>  > a[integer(0)]
> integer(0)
>  > a[-integer(0)]
> integer(0)
>
> When it comes to the function integer(), the R Help file says:
>
> "Value: integer creates a integer vector of the specified length. Each
> element of the vector is equal to 0."
>
> But we see below that integer(0) is some kind of null vector, that is,
> no numbers are represented by integer(0):
>
>  > class(integer(0))
> [1] "integer"
>  > length(integer(0))
> [1] 0
>
> So my question: in the expression a[-integer(0)], what happens exactly
> with the index -integer(0)? We see that integer(0), although of class
> integer, does not represent any numbers, as its length is zero, so it
> seems to me that it makes no sense to calculate its negative
> -integer(0). What exactly is -integer(0)?
>
> In particular, why a[-integer(0)] is not the whole vector a, that is,
> [1] 1 2 3 4 5? In the example below, if the invalid index -99 is
> presented to a, the result is the whole vector:
>
>  > a[-99]
> [1] 1 2 3 4 5
>
> If -integer(0) is an invalid index, why do we have this?
>
>  > a[-integer(0)]
> integer(0)
>
> Why a[-integer(0)] is not the whole vector a?
>
> Thank you very much.
>
> Paulo Barata
>
> Rio de Janeiro, Brazil
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.