Skip to content
Back to formatted view

Raw Message

Message-ID: <CA+hbrhX6tH-1R3k_rLZF+KMz--hJN8tRhJm7s5unbJd9Uob9gw@mail.gmail.com>
Date: 2022-07-02T06:18:56Z
From: Peter Langfelder
Subject: Subsetting a vector using an index with all missing values
In-Reply-To: <CAHqSRuQUBBsDFxNUHBYmBkoDmUG1FOY_aoX9oVS9=afuX35J+Q@mail.gmail.com>

Ah, thanks, that makes sense.

Peter

On Fri, Jul 1, 2022 at 10:01 PM Bill Dunlap <williamwdunlap at gmail.com> wrote:
>
> This has to do with the mode of the subscript - logical subscripts are repeated to the length of x and integer/numeric ones are not.  NA is logical, NA_integer_ is integer, so we get
>
> > x <- 1:10
> > x[ rep(NA_integer_, 3) ]
> [1] NA NA NA
> > x[ rep(NA, 3) ]
>  [1] NA NA NA NA NA NA NA NA NA NA
>
> -Bill
>
>
> On Fri, Jul 1, 2022 at 8:31 PM Peter Langfelder <peter.langfelder at gmail.com> wrote:
>>
>> Hi all,
>>
>> I stumbled on subsetting behavior that seems counterintuitive and
>> perhaps is a bug. Here's a simple example:
>>
>> > x = 1:10
>> > x[ rep(NA, 3)]
>>  [1] NA NA NA NA NA NA NA NA NA NA
>>
>> I would have expected 3 NAs (the length of the index), not 10 (all
>> values in x). Looked at the documentation for the subsetting operator
>> `[` but found nothing indicating that if the index contains all
>> missing data, the result is the entire vector.
>>
>> I can work around the issue for a general 'index' using a somewhat
>> clunky but straightforward construct along the lines of
>>
>> > index = rep(NA, 3)
>> > x[c(1, index)][-1]
>> [1] NA NA NA
>>
>> but I'm wondering if the behaviour above is intended.
>>
>> Thanks,
>>
>> Peter
>>
>> ______________________________________________
>> 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.