Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

r - Indexing integer vector with NA

I have problems understanding this. I have an integer vector of length 5:

x <- 1:5

If I index it with a single NA, the result is of length 5:

x[NA] 
# [1] NA NA NA NA NA

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

x <- c(NA, 2, 4)
x[NA] 
# NA NA NA.

So this cannot be the solution. My second approach is that x[NA] is indexing but then I do not understand

  1. Why this gives me five NA's
  2. What NA as an index means. x[1] gives you the first value but what should be the result of x[NA]?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...