Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider the following:

seq(from=10,to=30)[c(4,8)]
[1] 13 17

seq(from=10,to=30)[c(NA,8)]
[1] NA 17

seq(from=10,to=30)[c(NA,NA)]
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

To me the result of the latter is inconsistent with how the other two examples are handled by R and has cost me quite unpleasant debugging pains.

Might this be considered a bug?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Not sure if it is a bug - I suspect that depends on your point of view, but it is a subtlety of how indexing works. The quick solution is to change your third example to:

seq(from=10,to=30)[as.numeric(c(NA,NA))]

The reason is that c(NA,NA) is a logical vector, so the logical subsetting (which involves recycling the vector) is used, whereas having at least one non-NA causes the vector to be promoted to an integer vector. Likewise this could be implemented as:

seq(from=10,to=30)[c(NA_integer_,NA_integer_)]

See ?'[' for specifics of indexing if you're not familiar with them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...