order()函数失效求助:按数据框首行升序排序失败
order() Not Working as Expected for Sorting Data Frame by First Row Hey there! Let's break down why your order() function is giving unexpected results, and fix it step by step.
The Root Cause
Your issue comes down to data type mismatch in your data frame. When you use rbind(values, labels):
valuesis a numeric vector, butlabelsis a character vectorrbind()forces all elements to the same type (character, since it's more flexible), so your first row (df[1,]) ends up being a character vector instead of numeric.
When you sort character strings like "11", "10", "2", R compares them lexicographically (like dictionary order): "1" comes before "2", so "10" and "11" end up before "2"—that's exactly the weird order you're seeing!
The Fix
We need two key adjustments:
- Create the data frame in a way that preserves the numeric type of the first row
- Use
order()correctly on the numeric values
Step 1: Correctly Build the Data Frame
Instead of rbind(), use t() (transpose) on a column-bound dataset to keep types intact:
values <- c(11,10,9,8,7,6,5,4,3,2,1) labels <- c("A","B","C","D","E","F","G","H","I","J","K") # Bind as columns first, then transpose to get rows df <- as.data.frame(t(cbind(values, labels)), stringsAsFactors = FALSE) # Set meaningful row names row.names(df) <- c("values", "labels")
Now df[1,] is a numeric vector, which is what we need for proper sorting.
Step 2: Sort with order()
Now you can use either of your original order() calls (they'll work correctly now):
# Option 1: Direct order call newdf <- df[, order(df[1,])] # Option 2: Using with() (though not necessary here, but still valid) newdf <- df[, with(df, order(df[1,]))] # Print the result print(newdf)
Expected Output
You'll now get the correct ascending sort based on the first row's numeric values:
X11 X10 X9 X8 X7 X6 X5 X4 X3 X2 X1 values 1 2 3 4 5 6 7 8 9 10 11 labels K J I H G F E D C B A
Quick Check (If You Want to Verify Types)
To confirm your first row is numeric, run:
class(df[1,]) # Should return "numeric" instead of "character"
内容的提问来源于stack exchange,提问作者Rodney Beard

