burgundy7
burgundy7

Reputation: 5

Ordering rows in R

I have a question about ordering data in R:

data<-letters
data<-sample(data)
order<-c(1:26)
data<-as.data.frame(cbind(data,order))
data<-arrange(data,order)

data$order

[1] 1  10 11 12 13 14 15 16 17 18 19 2  20 21 22 23 24 25 26 3  4  5  6  7  8  9 

How can I make the order be as 1, 2, 3, 4, 5 instead?

Upvotes: 0

Views: 232

Answers (4)

Badger
Badger

Reputation: 1053

sort(data) should do this just fine. Check out ?sort as there is an argument to chose ascending or descending.

Upvotes: 0

IRTFM
IRTFM

Reputation: 263471

DON'T USE as.data.frame(cbind(data,order)) # just use either data.frame or as.data.frame

And please throw away any tutorial that taught you that. It's an abomination!

Upvotes: 3

MrFlick
MrFlick

Reputation: 206546

When you cbind elements, they must be all the same type, when you combined those characters and numeric values in the as.data.frame command, you forced everything to character and then when you make a data.frame they are converted to factors. Those are sorted lexicographical by default. If you want them to sort like numbers, I suggest you keep them as numbers. So

data<-data.frame(data,order)

Is a better choice. Alternative, you can convert the character values of the labels to numeric and sort

data<-arrange(data,as.numeric(as.character(order)))

but that's a lot of unnecessary work.

Upvotes: 0

joran
joran

Reputation: 173697

The monstrosity that is as.data.frame(cbind()) strikes again. There is a function for creating data frames. It's called data.frame(). Use it! ;)

data<-data.frame(data = data,order = order)
data<-arrange(data,order)

When you cbind a factor (or character) with a numeric vector, as documented in ?cbind, you'll get a matrix, and hence lots of probably unwanted coercion.

Upvotes: 4

Related Questions