0

I am trying to order a simple numeric vector including NAs. While running test, I encountered some unexpected behavior of the order function.

The third line is not what I would have expected:

order(c(3,5,4,NA))
[1] 1 3 2 4
order(c(3,5,4,NA), na.last = TRUE)
[1] 1 3 2 4
order(c(3,5,4,NA), na.last = FALSE)
[1] 4 1 3 2

for the last result I would have expected NA to come first in the sequence:

order(c(3,5,4,NA), na.last = FALSE)
[1] 2 4 3 1

similar to these two "correct" examples:

order(c(3,NA,5,4), na.last = FALSE)
[1] 2 1 4 3

order(c(NA,3,5,4), na.last = FALSE)
[1] 1 2 4 3

R version 3.5.2 (2018-12-20)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux 9 (stretch)

Btw, I also tried to run:

base::order(c(3,5,4,NA), na.last = FALSE)
[1] 4 1 3 2

What am I missing?

joran
  • 169,992
  • 32
  • 429
  • 468
sdittmar
  • 365
  • 2
  • 14
  • I'm not sure I follow. "Putting the NA first" in your example means that the first returned element should be 4, if the NA is last. – joran Mar 27 '19 at 18:59
  • The `na.last` argument defines where in the order the NA is placed, either at the start or at the end of the order list, is my understanding. That's why NAs should always have either the highest or lowest order, depending on the `na.last` setting. – sdittmar Mar 27 '19 at 19:03
  • Right, so if the NA is the last element (it is) and you say `na.last = FALSE`, that means it should put the 4th (last) element first. Which it does. – joran Mar 27 '19 at 19:08
  • I think you're confused about what `order` does (which is common, it is somewhat confusing). It returns a vector that if you index the original vector by it, you end up with everything in the desired order. So the correct answer really is 4th element, 1st element, 3rd element and then 2nd element. – joran Mar 27 '19 at 19:11
  • I rolled back your edit because it didn't meaningfully change your question, and since you didn't also update the output, it made the question considerably more confusing. If you want to edit with a new example, please be sure to change everything so it's consistent. – joran Mar 27 '19 at 19:15
  • Of cause!!! Thank you! It's been a long day... Can you copy it in as answer? – sdittmar Mar 27 '19 at 19:15

0 Answers0