-1

Can someone please explain why "0" is not included as the first unit to count when you do the order function? I have samples with IDs and they start at 0,1,2,3,4,...etc. When I do the order function, the ID numbers start at 1 rather than 0. Can someone explain why that is and also how to solve this problem?

I have a dataframe with several columns and one of the columns is ID and i want to sort the entire dataframe according to that column. The only thing is that I tried order, but it started at one. On excel, you can do custom sort and have it from smallest to largest. That's kind of what I am looking for, but I have tried everything and still nothing. Is there a way to do this?

UPDATE: So I learned what was going wrong. So the 0s were being eliminated due to running certain lines of code before others. I changed the order to be the ideal order of lines running, I fixed it and once I ran order() again, this time it did start at 0 and did not delete the 0s. I know that this was a stupid mistake and oversight, and I apologize to all of you that had to read this atrocious question, especially since I am new to R. Thank you all for your help.

Lasarus9
  • 83
  • 9
  • 1
    `order` gives the index. Indexing in `R` starts at 1. You need `vec[order(vec)]` or more easily `sort(vec)` – akrun Nov 15 '18 at 19:41
  • 1
    If the vector to be ordered has a zero it will be included. As a matter of fact, you can even `order` negative values. But the return value of `order starts at `1`. – Rui Barradas Nov 15 '18 at 19:43
  • I have a dataframe with several columns and one of the columns is ID and i want to sort the entire dataframe according to that column. The only thing is that I tried order, but it started at one. On excel, you can do custom sort and have it from smallest to largest. That's kind of what I am looking for, but I have tried everything and still nothing. – Lasarus9 Nov 15 '18 at 19:59

1 Answers1

4

Order returns the index values of the elements in a vector in a sorted order, so that, for example:

x<-c(5,3,0,7)
order(x)
[1] 3 2 1 4

x[order(x)]
[1] 0 3 5 7

This is useful if, for example, you want to sort one vector by the order of another.

If you want the response to be the actual vector values sorted in order, use sort:

sort(x)
[1] 0 3 5 7
iod
  • 7,412
  • 2
  • 17
  • 36
  • I have a dataframe with several columns and one of the columns is ID and i want to sort the entire dataframe according to that column. The only thing is that I tried order, but it started at one. On excel, you can do custom sort and have it from smallest to largest. That's kind of what I am looking for, but I have tried everything and still nothing. – Lasarus9 Nov 15 '18 at 19:58
  • 1
    if you run `df[order(df$id),]`, your df will be re-ordered with the lowest ID (0, in this case) at the top. Alternatively, if you want to use the tidyverse, you can do `arrange(df, id)`. – iod Nov 15 '18 at 20:53