如何用data.table的setcolorder按另一数据框列重排数据框列
setcolorder Error When Reordering Columns with data.table Hey there! Let's sort out this error you're seeing with setcolorder. The problem here is pretty straightforward: the setcolorder function doesn't accept a key= argument — that's not one of its parameters.
Why You Got the Error
When you ran gf3<-setcolorder(df1, key=df2$names), you tried to pass the column order vector using a named argument that doesn't exist. setcolorder expects the new column order as its second positional argument (no need for a parameter name like key).
The Correct Implementation
First, a quick note about data.table behavior: most set* functions like setcolorder modify the data.table in-place (they change the original object directly). If you want to keep your original df1 intact, make sure to copy it first with copy().
Here's the step-by-step fix:
- Load the
data.tablepackage (if you haven't already) - Create a copy of
df1to avoid modifying the original data - Use
setcolorderwith just the target data.table and your desired column order vector
library(data.table) # Example data matching your scenario df1 <- data.table(five = 1:5, two = 6:10, three = 11:15, one = 16:20, four = 21:25) df2 <- data.table(names = c("one", "two", "three", "four", "five")) # Make a copy of df1 first (critical if you want to preserve the original) gf3 <- copy(df1) # Reorder columns directly with df2$names — no key= argument! setcolorder(gf3, df2$names) # Check the result gf3
Key Notes to Remember
- Always use
copy()if you don't want to alter the originaldata.table— skipping this will changedf1's column order permanently. - Double-check that every name in
df2$namesexists indf1— if there's a mismatch,setcolorderwill throw an error about missing columns. setcolorderis designed for speed (it's optimized fordata.table), so it doesn't return the modified table — that's why we modify the copied table directly.
内容的提问来源于stack exchange,提问作者Jakhongir Alidjanov

