Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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!

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top