ruedi - 1 year ago 65

R Question

I have problems understanding this codeline

`x <- 1:5; x[NA]`

[1] NA NA NA NA NA

My first idea was that R checks whether 1-5 is

`NA`

`x <- c(NA, 2, 4); x[NA]`

NA NA NA.

So this cannot be the solution. My second approach is that

`x[NA]`

- Why this gives me five
`NA's`

- What NA as an index means. gives you the first value but what should be the result of
`x[1]`

?`x[NA]`

Answer Source

Compare your code:

```
> x <- 1:5; x[NA]
[1] NA NA NA NA NA
```

with

```
> x <- 1:5; x[NA_integer_]
[1] NA
```

In the first case, `NA`

is of type logical (`class(NA)`

shows), whereas in the second it's an integer. From `?"["`

you can see that in the case of `i`

being logical, it is recycled to the length of `x`

:

For [-indexing only: i, j, ... can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. i, j, ... can also be negative integers, indicating elements/slices to leave out of the selection.