Can't sort data frame by column name with a "-" in it

While I agree with your recommendation about usage of - in column headings, your code fragment is incorrect and misses the closing ), ]:

df[order(-df[4, ]

will order the columns descending by the values in row 4 (if you add ), ] to the statement).

order() returns a list of row numbers that would sort df but you need to also specify the columns:

df.sort <- df[order(-df[ , 4]), ]

df[row, column] so order(-df[ , 4]) sorts rows in df descending by column 4. Adding another , ] will pick all columns in the final result.

1 Like