0

I have a dataframe and I want to order it by a character column and by a date or numeric column.

It works when I order both in ascending order:

dataframe <- dataframe[order(dataframe$stringvariable, dataframe$numericvariable),]

However, I cannot figure out how to order it by the numeric variable in descending order.

When I try the code below, I get error message "Error in -dataframe$numericvariable : invalid argument to unary operator:"

dataframe <- dataframe[order(dataframe$stringvariable, -dataframe$numericvariable),]

When I try the code below instead, I get error message "argument 2 is not a vector" and "Unknown or uninitialised column: numericvariable."

dataframe <- dataframe[order(dataframe$stringvariable, rev(dataframe$numericvariable)),]

It works when I only order by numericvariable, but I cannot figure out how to do this when I want to order by more than one column.

Rene
  • 81
  • 5
  • 2
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 26 '22 at 19:19
  • 1
    `order(letters, -(1:26))` works, so it is not just a matter of one field being character and one numeric. What seems more likely is that your `$numericvariable` is really strings of numbers. Please add reproducible sample data. – r2evans Aug 26 '22 at 19:27
  • 1
    and fyi if you want to reverse order a string or factor variable, you can use `xtfrm`: `order(-xtfrm(letters))` – rawr Aug 26 '22 at 19:31

0 Answers0