user1987607
user1987607

Reputation: 2157

sorting numerical values R

I have a table (out) that looks like this:

V1    V2    V3
A     x     0
A     y     1
A     z     10
A     a     11
A     b     12
...   ...   ...
A     c     2
A     d     21
A     e     22
...   ...   ...
A     f     3

I sorted this table based on V3 with this function

sorted.out <- out[order(out$V3), ]   

However I want the values in V3 in numerical order like 1,2,3,4, ..., 10,11,12, ... and not like it is now 1,10,11,12, ...

How can I do this?

When I use str(out) my V3 comes out as a factor variable. I should change it to numerical probably?

Upvotes: 5

Views: 20554

Answers (1)

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12819

Try sorted.out <- out[order(as.numeric(as.character(out$V3))), ]

Note that you must first convert to character, then to numeric. Otherwise you may end up with the order according to the factors.

Upvotes: 10

Related Questions